简体   繁体   English

在 Java 的 Linkedlist 实现中,head 如何更新新节点

[英]How head is updating with new nodes in Linkedlist implementation in Java

I am learning implementation of LinkedList in Java.我正在学习 Java 中 LinkedList 的实现。 While doing so I am not understanding the concept how head is updating with new nodes after executing below code in LinkedList.java though we are not updating head.这样做时,我不理解在 LinkedList.java 中执行以下代码后,head 是如何更新新节点的概念,尽管我们没有更新 head。

n.next = node;

Please let me understand the concept.请让我理解这个概念。 Thanks in advance.提前致谢。

Node.java节点.java

public class Node {
    int data;
    Node next;  
    }

LinkedList.java链表.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主.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();
    }
}

Head is set to the first node you create in the list, and never changes. Head 设置为您在列表中创建的第一个节点,并且永远不会更改。 when adding new nodes, the loop goes to the end of the list (finds the "tail" node with next == null) and sets the new node as its' (the tail's) "next".添加新节点时,循环转到列表的末尾(找到 next == null 的“尾”节点)并将新节点设置为其(尾的)“下一个”。

the head is not updated, it always stays the same reference to the first element of the list.头部没有更新,它始终保持对列表第一个元素的相同引用。 any new node is added to the end of the list.任何新节点都会添加到列表的末尾。

of course, you can keep a referecnce to the tail node and save some time looping over the list.当然,您可以保留对尾节点的引用并节省一些时间循环遍历列表。

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

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