简体   繁体   中英

How head is updating with new nodes in Linkedlist implementation in Java

I am learning implementation of LinkedList in Java. 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.

n.next = node;

Please let me understand the concept. Thanks in advance.

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();
    }
}

Head is set to the first node you create in the list, and never changes. 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".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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