0

I was under the impression that creating a variable and setting it equal to an object would act as a reference, ie. changing the original object would subsequently "change" the variable as well. The code i'm specifically referring to is as follows:

public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } ... ListNode l1 = ... // l1 is an input ListNode iterator = head; // copying l1 into a new list, starting with 'head' ... iterator.next = l1; l1 = l1.next; 

The last piece of code loops multiple times. Why is it that, when we set iterator.next = l1, it acts as copying the 'l1' object, instead of creating a reference to l1? Shouldn't the result just be a bunch of copies of l1, rather than at each step of the way?

1

2 Answers 2

7

You're referring to pointers. When you create a new pointer to an existing object, it doesn't update the original object's pointer.

For example:

ListNode l1 = ... ListNode iterator = ... iterator.next = l1 

In this case, iterator.next points to the same object that l1 points to. If I then change the pointer l1 using the following line:

l1 = l1.next 

l1 is changed here, meaning the pointer, not the object. I can create as many pointers as I want to the same object:

Object a = ... Object b = a Object c = a Object d = a 

All of these pointers (a, b, c, d) point to the same object, and I can use them interchangeably, but if I change one of the pointers to point to a different object:

b = new Object(); 

b no longer points to the same object, but that does not change a, c, or d. Those all point to the same original object.

Sign up to request clarification or add additional context in comments.

2 Comments

Gotcha. So if 'l1' were instead to be declared as an object, say as l1 = new ListNode(...), then 'iterator' would change with l1 = l1.next, correct?
l1 = l1.next will change l1 to point to whatever object was stored in l1.next. It will not change iterator.
0

Your code can also be referred to for removing an element from a linked list.

As stated by @David so far, iterator.next points to the object that l1 points to and l1 = l1.next the pointer l1 changes. This simply means iterator.next will now points to what l1.next points to.

Since our ListNode is unidirectional, starting from iterator (as the head of the list and assuming it's not null), we can no longer access the object referenced by l1 since iterator.next points to l1.next.

Since we cannot navigate backward, we can no longer access what l1 points to.

And in that case we can consider that the object referenced by l1 has been removed from the list that starts with iterator as the head of the list.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.