I am trying to understand the difference between node1.next = node3
and node2 = node3
.
In the linked list, node1.next = node3
gets rid of node2
. But node1.next
points to node2
anyways so why doesn't node2 = node3
not work in the following code?
public class LinkedList {
LinkedList head = null;
LinkedList next = null;
int data = 0;
public static void main(String[] args) {
LinkedList node1 = new LinkedList();
LinkedList node2 = new LinkedList();
LinkedList node3 = new LinkedList();
node1.data = 1;
node1.next = node2;
node2.data = 2;
node2.next = node3;
node3.data = 3;
node3.next = null;
node2 = node3;// If I replace with node1.next = node3; it works
LinkedList h = node1;
while (h.next != null) {
System.out.println(h.data);
h = h.next;
}
}
}