我正在尝试理解Java中链接列表中的方法,但我仍然遇到了一些问题。
所以我从类Element开始:
class Element {
int val; // can be anything like String etc.
Element next; // Pointer to the next Element
然后我有班级列表:
public class List {
Element head = null; // Beginning of the list (head)
现在的方法:请看评论。首先,我从一个方法开始,该方法将Element插入列表的开头。
public void insertAtBegin (int x){
Element n = new Element(); // We create a new Object Element called n
n.val = x; // We pass the value of x to the object n with the attribute int val (Is that right?)
n.next = head; // What happens here?
head = n; // The new Element n becomes the head
}
第二种方法在列表的末尾插入一个元素:
public void insertAtEnd(int x){
Element n = new Element();
n.val = x;
if (head == null){ // If the list is empty
head = n; // we insert the Element n as the first element
}
else{
Element h = head; // I think this helps as a reference right?
while (h.next != null){ // While the pointer of the head isn't empty
h = h.next; // our Element h becomes the next Element added to the list
}
h.next = n; // If none of the cases above apply, the Element h ist just added at the end of the list right?
}
}
如果我现在想要在一定数量后插入一个元素,那么该方法会是什么样子?不是在开始时,也不是在最后。从理论上讲,我首先要看头是否为空。然后我将指针放在我的特定元素上,例如4我要插入的新元素。以及新插入元素到即将到来的元素的指针。但我不知道如何把它放在代码中..
我还有一个方法可以删除列表的最后一个元素并在开头插入它。有人可以评论一下它是如何工作的吗?
public void lastToBegin(){
if (head != null && head.next != null){
Element e = head;
while(e.next.next != null){
e = e.next;
}
Element h = e.next;
e.next = null;
h.next = head;
head = h;
}
}
我有更多方法,但我首先要了解基础知识。 感谢任何帮助,谢谢。
答案 0 :(得分:0)
如果要在列表中的某个索引处插入元素,它看起来与您必须在最后插入的方法非常相似,除非您必须停在正确的索引处,而不是在最后,并且你必须确保添加'尾巴'列表中您要插入的元素。
所以你的代码看起来像这样:
r+1