java - 在 Java 的 Linkedlist 实现中,head 如何使用新节点进行更新
问题描述
我正在学习 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 的“尾”节点)并将新节点设置为其(尾的)“下一个”。
头部没有更新,它始终保持对列表第一个元素的相同引用。任何新节点都会添加到列表的末尾。
当然,您可以保留对尾节点的引用并节省一些时间循环遍历列表。
推荐阅读
- python - 我该如何解决这个问题:ValueError invalid literal for int() with base 10: ''? Python
- r - 如何为 R 主题模型正确编码 UTF-8 txt 文件
- perl - 如何构建和安装本地 Perl 模块
- java - RObject.isExists() 检查内存还是服务器?
- javascript - 带有生涩滚动的 HTML/CSS 粘性标题
- microsoft-graph-api - 尝试存档团队时 Microsoft Graph API 502 Bad Gateway
- c# - 找不到方法 - AWS .NET Core 3.1 Mock Lambda 测试工具
- python - 熊猫数据框可视化数字列的不同箱内分类列的不同值的百分比
- html - 角覆盖隐藏在粘性标题下
- python - tsv 文件中的行到单独的数组中