Linked List fundamental concepts 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 -&gt; 2 -&gt; 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
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.