Reputation: 1329
I am working on adding an item to the end of a linked list (this isn't homework...just an exercise for myself).
Here is the program:
public class CustomLinkedList {
private static Node head = null;
private int size = 0;
public static void main(String[] args) {
CustomLinkedList myList = new CustomLinkedList();
myList.add(5);
myList.add(9);
myList.add(3);
System.out.println("List Size: " + myList.size);
myList.print();
}
private int size() {
return this.size;
}
private void print() {
Node temp = head;
for (int i=0; i<=size-1;i++){
System.out.print(temp.value + " ");
temp = temp.next;
}
System.out.println();
}
private void add(int value) {
if (head == null) {
head = new Node();
head.value = value;
head.next = null;
size++;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = new Node();
(temp.next).value = value;
size++;
}
}
}
Here is my Node class:
public class Node {
public int value;
public Node next;
public int getValue(){
return this.value;
}
}
Here is what I think is happening:
1. I have an original/ongoing list starting with "head."
2. I want to add to that list.
3. To add to it, I need to find the end of it. I do that by creating a new node called temp (which is just a copy of the original list).
4. I traverse the copy (temp) until I reached the end.
5. Once I reach the end, I create a new node.
To me, this is where my code stops. Now, in my mind, I need to add code that says, "Alright, you have your new node, you know where it needs to go, so lets go through the real list and add it."
But I don't have that. According to my debugger (image below), the right thing is happening, but I don't see the magic that is adding the new node to the original list. How is this working?
Edit:
I did look at other implementations (like the one here); it looked very similar. However, I still couldn't find why it works without assigning temp to head (or to head.next). I get Linked Lists in theory I believe. I just don't understand why this bit works.
Upvotes: 0
Views: 129
Reputation: 424983
Your confusion is that temp
is different to head
. It's not.
They are both variables holding references to the same Node
object. Changes made via either variable are reflected in the (same) object they reference. When you add a Node
to temp
, you add it to the real list.
Upvotes: 1