As the title implies, I trying to implement a doubly linked list in java.
However while working on it I came across something I have trouble understanding.
For context here is my code:
public class Doublelist{
Node head;
public static class Node{
private int data;
private Node prev;
private Node next = null;
public Node (int data){
this.data = data;
prev = null;
next = null; //default case for new node
}
public String toString(){
String i = Integer.toString(data);
return i;
}
//Method below handles inputting data at end of the linked list
public static Doublelist add_node_end(Doublelist list, int data){
Node add_node = new Node(data);
add_node.next = null;
if (list.head == null){
list.head = add_node;
list.head.prev = null;
}
else{
Node travel = list.head;
while (travel.next != null){
travel = travel.next;
}
add_node.prev = travel;
travel.next = add_node;
}
return list;
}
public static void modify_obj_test (Doublelist list){
Node travel = list.head;
System.out.println("Travel initially: "+ travel);
Node currnode = travel;
travel.next.next = null;
System.out.println("Travel.next.next: "+ travel.next.next);
System.out.println("Currnode.next.next: "+ currnode.next.next);
}
}
HERE is the method that shows the issue I am having: (Note: I created this method just to show the trouble in my understanding, doesn't do anything for the linked list )
public static void modify_obj_test (Doublelist list){
Node travel = list.head;
System.out.println("Travel initially: "+ travel);
Node currnode = travel;
travel.next.next = null;
System.out.println("Travel.next.next: "+ travel.next.next);
System.out.println("Currnode.next.next: "+ currnode.next.next);
}
The output of this gives the following
Travel initially: 1
Travel.next.next: null
Currnode.next.next: null
However when I change this function and I do the following
public static void modify_obj_test (Doublelist list){
Node travel = list.head;
System.out.println("Travel initially: "+ travel);
Node currnode = travel;
travel = travel.next;
travel = travel.next;
travel = null;
System.out.println("Travel.next.next: "+ travel);
System.out.println("Currnode.next.next: "+ currnode.next.next);
}
The output then becomes
Travel initially: 1
Travel.next.next: null
Currnode.next.next: 3
My question is, why is it that the currnode.next.next is being modified when I make travel.next.next = null, however when I shift down the list one by one by doing travel = travel.next, It doesn't effect the currnode variable?
I thought that by making currnode = travel, was sorta like making a temp variable in C where a copy of the value is kept safe while an operation goes on, I didn't realize that depending on how I modify the travel variable it can also affect the currnode variable.