[英]How head is updating with new nodes in Linkedlist implementation in Java
我正在学习 Java 中 LinkedList 的实现。 这样做时,我不理解在 LinkedList.java 中执行以下代码后,head 是如何更新新节点的概念,尽管我们没有更新 head。
n.next = node;
请让我理解这个概念。 提前致谢。
节点.java
public class Node {
int data;
Node next;
}
链表.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));
}
}
主.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 设置为您在列表中创建的第一个节点,并且永远不会更改。 添加新节点时,循环转到列表的末尾(找到 next == null 的“尾”节点)并将新节点设置为其(尾的)“下一个”。
头部没有更新,它始终保持对列表第一个元素的相同引用。 任何新节点都会添加到列表的末尾。
当然,您可以保留对尾节点的引用并节省一些时间循环遍历列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.