Reputation: 93
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?
Upvotes: 0
Views: 178
Reputation: 1614
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.
Upvotes: 0
Reputation: 25412
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.
Upvotes: 7