Why can't I use head directly in this linked list problem instead of initializing and using ptr?

59 views Asked by At

I was going through this solution for implementing a doubly linked list when I came across this doubt

public class Solution
{
    public static Node constructDLL(int []arr) {
        Node head = new Node(arr[0]);
        Node ptr = head;
        for(int i = 1; i<arr.length; i++) {
            Node node = new Node(arr[i]);
            ptr.next = node;
            node.prev = ptr;
            ptr = node;
        }
        return head;
    }
}

Why can't I use head directly in this linked list problem instead of initializing and using ptr like this?

public class Solution
{
    public static Node constructDLL(int []arr) {
        Node head = new Node(arr[0]);
  
        for(int i = 1; i<arr.length; i++) {
            Node node = new Node(arr[i]);
            head.next = node;
            node.prev = head;
            head= node;
        }
        return head;
    }
}

And if ptr refers to head, why does returning ptr return one value but returning head returns all the values in the array? I'm new to linked list and these things have got me super confused.

2

There are 2 answers

0
trincot On

If you would perform return ptr instead of return head in the first solution, you would actually do the same as in the second. The name of the variable that you use in the return statement is of course not of importance; it is the node (reference) that you return that is important.

And so it is clear that with that modification you return the last node that was appended to the list (see last iteration of the loop). That node has its next field still at null. The caller would have to navigate via the prev references back to the head to eventually find it.

0
SAMEER KHANNA On

Initializing a node as head and using ptr for traversal helps in visualizing the head node as the starting point of the doubly linked list. If you use head directly to build the doubly linked list, you will lose the starting node and later, you will have to traverse backwards to get the starting node.

If you return ptr in the first case, then ptr is the last node of the linked list and hence will return only one node, whereas head is the first node and will return all the nodes.