在链表中实现在列表末尾插入项目的方法时,这是我想到的代码,
public void insertEnd(Object item){
SListNode current=head;
while(current.next!=null){
current=current.next;
}
current.next=new SListNode(item);
size--;
}
但由于它不起作用,我从一本书上查了一下,意识到我必须添加这行
current=current.next;
在while循环之后再次这样代码就变成了
public void insertEnd(Object item){
SListNode current=head;
while(current.next!=null){
current=current.next;
}
current.next=new SListNode(item);
current=current.next;
size--;
}
为什么需要添加该行(新代码中的第 7 行),因为 current.next 通过 current.next=new SListNode(item);
我的第二个问题是为什么当列表为空时我必须考虑一个单独的情况?我得到一个空指针异常错误。
谁能用图解释一下
最佳答案
没有线 current=current.next;你将永远陷入 while 循环,并且在第一次迭代时永远不会创建新节点(第一次插入它会引发异常)
public class Test2 {
SListNode head;
public void insertEnd(String item) {
SListNode current = head;
while (current.next != null) {
current = current.next;
}
current.next = new SListNode(item);
// this line does not have any meaning, because it is out of while loop scope
current = current.next;
}
public static void main(String[] args) {
Test2 test2 = new Test2();
test2.test();
}
private void test(){
// keeping head reference
head = new SListNode("1");
insertEnd("2");
insertEnd("3");
insertEnd("4");
System.out.println("HEAD "+head.item);
SListNode init = head.next;
while ( init != null ){
System.out.println("ADDED "+init.item);
init = init.next;
}
}
class SListNode {
SListNode next;
String item;
public SListNode(String item) {
this.item = item;
}
}
好的,这是一个重构代码(简化)。有那条线或没有程序都可以。
关于java - 链表添加一个元素到列表的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23428073/