0019. Remove Nth Node From End of List
Medium | Linked List + Two Pointer | 12 ms (98.94%), 13.3 MB (72.36%)
Source: LeetCode - Remove Nth Node From End of List GitHub: Solution / Performance
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
Use a hash table to record each node's location needs O(n). Instead, we could manipulate two pointers to create a gap between two pointers to find the target node, and that only required O(1) space complexity.
Move the fast-pointer forward to create
n
gaps apart from the slow-pointerIf the fast-point now points to null, it means the first node is the one to be removed
Move forward the fast-pointer and slow-pointer together until the next node of the fast-pointer is null
Now, the next node of the slow-pointer is the one that needs to be removed. So then break the link by
slowP.next = slowP.next.next
and return the head
Last updated