0
$\begingroup$

I am trying to understand the basics of Linked List. The definition of my LinkedList class is as follows:

public class ListNode {
 int val;
 ListNode next;
 ListNode(int x) { val = x; }

Now I am facing a problem. My code is as follows:

ListNode dummy = new ListNode(0);
dummy.next =  head;
ListNode prev = dummy;
ListNode slow = head;
head.next = null;
prev.next = slow;

ListNode temp = slow.next;
prev.next = temp;

System.out.println(dummy.next); //comes out null

Why is it coming out as null? dummy.next was pointing to head and I only changed slow and prev?

Can we use slow and head interchangeably? If yes, then why does this happen?

// head points to a Linked list starting from 1 in 1 -> 2 -> 3
ListNode curr = head;

while(curr.next!= null){
    curr= curr.next;
}

System.out.println(curr);
System.out.println(head); //these are different and head does not change
$\endgroup$

closed as off-topic by Yuval Filmus, Discrete lizard, Evil, David Richerby, vonbrand Jul 6 '18 at 15:14

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions about software development or programming tools are off-topic here, but can be asked on Stack Overflow." – Yuval Filmus, Discrete lizard, Evil, David Richerby, vonbrand
If this question can be reworded to fit the rules in the help center, please edit the question.

1
$\begingroup$

This has nothing to do with linked lists and everything to do with references (see also pointers). When you assign a mutable object to a variable, the variable holds a reference to the actual object: its memory address. If you assign the same object to two different variables, they both reference the same object; both variables internally hold the same memory address (and changing its members will change the underlying object). But when you then reassign one of those variables, that one now points to a different object again.

$\endgroup$
  • $\begingroup$ Hi! Thanks for answering. So, both dummy and prev point to the same object. But what confuses me is that what different am I doing in both the code snippets that causes this difference? Am I reassigning curr to a different object in the second and changing the pointer of prev and thus dummy in the first? Am I correct in understanding this? $\endgroup$ – crazyy_photonn Jun 30 '18 at 2:30
  • $\begingroup$ @crazyy_photonn In the first one, you "reach through" the reference to affect the data inside the actual object. In the second one, you change the variable to reference a different object. $\endgroup$ – Draconis Jun 30 '18 at 2:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.