Home > Back-end >  Java: Understanding the Singly Linked List implementation
Java: Understanding the Singly Linked List implementation

Time:11-14

Consider I am trying to add 10, 20 & 30. When I am adding the first node 10, the HEAD will be null. At this point, both HEAD and TAIL will point to the same node i.e. 10. Now when adding the second node 20, we are updating the TAIL's next to point to node 20. Since HEAD and TAIL share the same reference, HEAD also gets updated. All cool till here. After this, we are updating the tail reference. Now HEAD and TAIL won't share the common reference, right? But still how the HEAD is getting updated when we are adding the third node? I am so confused understanding it...

public class LinkedList {

    private class Node {

        private int data;
        private Node next;

        public Node(int data) {
            this.data = data;
        }

    }

    private Node head;
    private Node tail;

    public void add(int data) {

        var node = new Node(data);

        if (head == null) {
            head = tail = node;
            return;
        }       
        tail.next = node; 
        tail = node; // At this point, TAIL and HEAD are no longer connected, right? Still how HEAD gets updated when we are updating only TAIL?
    } 

}

CodePudding user response:

tail = node;

// At this point, TAIL and HEAD are no longer connected, right?

the tail is the last element that you add it's normal to do tail = node; to change the old tail and in this case the head will be connected with the new tail.

//Still how HEAD gets updated when we are updating only TAIL? after the first assign of the head it still the same during all the adds that we make inside the linkedlist

CodePudding user response:

When you did tail = node, the tail reference is updated to where node is referring. The head reference is still the same as what you set it the first time.

  • Related