java - 链表添加一个元素到列表的末尾

标签 java algorithm data-structures linked-list

在链表中实现在列表末尾插入项目的方法时,这是我想到的代码,

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); enter image description here

我的第二个问题是为什么当列表为空时我必须考虑一个单独的情况?我得到一个空指针异常错误。

谁能用图解释一下

最佳答案

没有线 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/

相关文章:

algorithm - 寻找top-k元素的平均时间复杂度

c# - 如何着手为 1 箱推箱子实现快速最短路径搜索?

c - c中的pf apply是什么?

c++ - Hashmap实现邻接表

java - 将参数作为 Wrapper 类传递并覆盖

java - 验证 Spring Data 查询参数中的集合不为空

java - 覆盖 web.xml 中 URL 模式 "default servlet"的 "/"行为

java - 将整数列表排序为 Java 中的字符串列表

c - HackerRank 上的对角线差异

java - 使用java实现Trie