【问题标题】:How head is updating with new nodes in Linkedlist implementation in Java在 Java 中的链表实现中,head 如何使用新节点进行更新
【发布时间】:2021-04-05 06:41:36
【问题描述】:

我正在学习 Java 中 LinkedList 的实现。这样做时,我不理解在 LinkedList.java 中执行以下代码后,head 是如何更新新节点的概念,尽管我们没有更新 head。

n.next = node;

请让我理解这个概念。提前致谢。

Node.java

public class Node {
    int data;
    Node next;  
    }

LinkedList.java

public class LinkedList {
Node head;
void insert(int data) {
    Node node = new Node();
    node.data = data;
    node.next = null;
    if(head==null) {
        head = node;        
    }else {
        Node n = head;
        while(n.next!=null) {
          n = n.next;
        }
        n.next = node; //--head is also updating with new nodes--//     
    }
}   
void display() {
    Node n = head;
do {
    System.out.println(n.data);
    n=n.next;
}
while(!(n.next==null));
}   
}

Main.java

public class Main {
    public static void main(String[] args) {            
        LinkedList list = new LinkedList();
        list.insert(10);
        list.insert(20);
        list.insert(30);
        list.insert(40);
        list.display();
    }
}

【问题讨论】:

  • 自己在insert 中检查head 是如何填充的(可能还有额外的System.out...)

标签: java linked-list


【解决方案1】:

Head 设置为您在列表中创建的第一个节点,并且永远不会更改。 添加新节点时,循环会转到列表的末尾(找到 next == null 的“尾”节点)并将新节点设置为其(尾)的“下一个”。

head 没有更新,它始终保持对列表第一个元素的相同引用。任何新节点都会添加到列表的末尾。

当然,您可以保留对尾节点的引用,并节省循环遍历列表的时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多