0

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?

asked Mar 6, 2021 at 20:16
1
  • 1
    It is called head for a reason. You should not be changing its value. Use a different reference. Call it current or something meaningful. Otherwise, how are you going to find the beginning of the list? Commented Mar 6, 2021 at 20:38

1 Answer 1

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
2
  • So will it remain in the memory after head points to the next element or get removed after it ?? Commented Mar 6, 2021 at 20:30
  • 1
    I believe after there are no more pointers to that object in memory - Java's garbage collector deletes it from memory. Commented Mar 6, 2021 at 20:31

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.