Reputation: 163
I am creating a function to remove the last node of a given list (inputted as an argument). The function itself is quite simple as shown below.
function popBack(list) {
var current = list.head,
previous;
while (current.next) {
previous = current;
current = current.next;
}
// console.log(current);
// console.log(previous.next);
// current = null;
// console.log(current);
// console.log(previous.next);
previous.next = null;
return list;
}
Since the next node in the list is referenced by the one before it, previous.next and current should point to the same object. This brings me to my question. If I set current
equal to null
, wouldn't that make previous.next
equal to null
as well? This doesn't seem to be the case, as previous.next
still references what current
used to be. Can anyone please explain why this is happening?
Thanks in advance.
Upvotes: 0
Views: 1195
Reputation: 142977
You are right that previous.next
and current
point to the same object. Let's call that object O
. That is,
previous.next
points to O
.current
points to O
.When you run the following code,
current = null;
it doesn't set O
to null, it only changes what current
points to. That is, after current = null;
is run, this is the new state:
previous.next
points to O
.current
points to null
.Upvotes: 2