Files
java-interview-lab/linked-list/output/03-delete-dry-run.txt
T

18 lines
785 B
Plaintext

Deleting from a singly linked list: which one pointer changes
=============================================================
remove the node at index 2 from 10 -> 20 -> 30 -> 40:
before: 10 -> 20 -> 30 -> 40 -> null
walk: before = node 20
found: before = 20, doomed = 30, doomed.next = 40
relink: 20.next = 40
after: 10 -> 20 -> 40 -> null
removing the head has no node before it, so the head variable itself changes:
before: head -> 10 -> 20 -> 30 -> null
head = head.next
after: head -> 20 -> 30 -> null
removing the tail needs the node before it, so it must be found by walking (and then tail moves back):
list 10, 20, 30, 40, 50: removeLast() returned 50 after following 3 links; list is now [10, 20, 30, 40]