首页 > 解决方案 > 在 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();
    }
}

标签: javalinked-list

解决方案


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

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

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


推荐阅读