We have a Linked List with 5 nodes
1 2 3 4 5
previous = pointing to 2
Head = pointing to 3
And if
prev.next=head.next;
head=head.next;
So i my question is if head is pointing to 3 and just deleted 3 by doing prev.next=head.next; and the new linked list will be
1 2 4 5
and now i do head=head.next; so how it will be going to 4 when i already delete the node with value 3 which was being pointed by head?
1 Answer 1
prev.next = head.next;
did not delete the node 3 from memory.
head is still pointing to 3, and head.next is still pointing to 4.
so writing head = head.next
is fine, you just change the value head is pointing to.
answered Mar 6, 2021 at 20:21
-
So will it remain in the memory after head points to the next element or get removed after it ??Ry_zen– Ry_zen03/06/2021 20:30:15Commented Mar 6, 2021 at 20:30
-
1I believe after there are no more pointers to that object in memory - Java's garbage collector deletes it from memory.Lior Elbaz– Lior Elbaz03/06/2021 20:31:20Commented Mar 6, 2021 at 20:31
lang-java
head
for a reason. You should not be changing its value. Use a different reference. Call itcurrent
or something meaningful. Otherwise, how are you going to find the beginning of the list?