繁体   English   中英

为什么 LinkedList 中的 add() 方法不起作用?

[英]Why does my add() method in LinkedList not working?

我只是在我的Linkedlist实现了add()方法,但它并没有真正起作用。 我认为“current = new Node(node.data);” 使对象指向一个新对象而不是更新原始对象,但我不知道如何解决它。 有什么办法可以正确更新这个节点吗? 请帮忙,谢谢。

class Node{
    int data;
    Node next; 
    Node(int data){
        this.data = data;
        this.next = null;
    }
    Node(int data, Node next){
        this.data = data;
        this.next = next;
    }
}
class LinkedList{
    protected Node head;
    protected int size;
    LinkedList(){};

    void add(int data)
    {
        Node node = new Node(data);
        if (head == null) {
            head = node;
        }else {
            Node current = head;
            while(current != null) {
                current = current.next;
            }
            current = new Node(node.data);
        }
        size++;
    }
    public int getSize() {
        return size;
    }
    public String toString()
    {
        Node current = head;
        String result = "";
        while(current != null) {    
            result += current.data +"->";
            current = current.next;
        }
        return result;
    }
}

你快到了。 你的问题就在这里

while(current != null) {
... }

current = new Node(node.data);

这就产生了一个新的节点,它应该坐在你的列表的末尾 但是你只将新实例分配给一个局部变量……然后它就会丢失,因为方法结束了。

相反,您必须更改循环,直到找到不为空的最后一个条目,以便current.next == null 然后简单地去:

current.next = new Node(node.data);

在 LinkedList 中,每个值都添加到顶部。 它不像添加到数组中。 因此,当您添加一个新节点时,不要尝试将其添加到末尾,而只需将其添加为新的 head 元素即可。

这很简单:

public void add(T item) {

    Node<T> next = new Node<>(item, head);
    this.head = next;
    size++;

}

如果要将 LinkedList 限制为仅 int,则可以将 T 替换为 int。

我希望这有帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM