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.
If you would perform
return ptrinstead ofreturn headin the first solution, you would actually do the same as in the second. The name of the variable that you use in thereturnstatement 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
nextfield still atnull. The caller would have to navigate via theprevreferences back to the head to eventually find it.