Anton Kim Anton Kim - 1 month ago 12
Java Question

Changing references to Objects java

Code from CCI book:

public class ListNode {

int val;
ListNode next = null;

ListNode(int x) {
this.val = x;
}


And this:

public void appendToTail(int d) {
ListNode end = new ListNode(d);
ListNode n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
}


Original: 5 -> 10 -> 15

As I understand, in this case "n" and "this" refer to same object yet, after debugging and stepping through:

"n" becomes 15 -> 20

"this" becomes 5 -> 10 -> 15 -> 20

How can this be? When I change "n", "this" should change as well?

So everything I did on "n" ,BESIDES appending 20, did not reflect on "this".

Answer

Inside your while loop you say:

n = n.next

When that line of code executes you change the value of n from "this" to n.next. This points to the current link object in the list and next points to a completely different object. As you walk your way through the linked list the value of n keeps updating as you pass through each link in the linked list.

When you get to the end of the linked list there is no next, i.e. value of n is null. So you exit the while loop and add a new link to the end of the linked list.

Comments