Remove Nth Node From End of List: Manipulating Linked Lists
The "Remove Nth Node From End of List" problem is a common challenge in linked list manipulation, focusing on removing a node from a specific position counting from the end of the list.
Problem Statement
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example
- Input: Linked List
1 -> 2 -> 3 -> 4 -> 5,n = 2 - Output: Modified List
1 -> 2 -> 3 -> 5
Solution Approach - Two Pointer Technique
Breaking Down the Solution
- Initialize Two Pointers: Use two pointers,
firstandsecond, both starting from a dummy node before the head. - Advance the First Pointer: Move
firstn+1 steps ahead, creating a gap of n nodes betweenfirstandsecond. - Move Both Pointers: Traverse the list with both pointers until
firstreaches the end. At this point,secondis just before the nth node from the end. - Remove the Nth Node: Adjust the
nextpointer of thesecondnode to skip the nth node.
Conclusion
The Remove Nth Node From End of List problem is an excellent exercise in pointer manipulation and demonstrates the two-pointer technique's usefulness in linked list problems. It highlights a common scenario in data structure manipulation and algorithm design.
Rust Solution
Option<Box<ListNode>> models the nullable, heap-owned next link that null covers in the TS version, and it's what pushes this solution away from the two-pointer walk: it first counts length with a shared-borrow while let Some(node) = cur loop, then re-walks to target = len - n through a mutable &mut dummy, stepping with cur.next.as_mut().unwrap(). Removal can't just overwrite a field the way JS does — you can't move a value out of a borrowed Option — so cur.next.take().unwrap() swaps in None to take ownership of the node before cur.next = removed.next splices its successor back in.
Go Solution
Go's *ListNode pointer is freely aliasable, so this ports the two-pointer walk almost verbatim — first := dummy and second := dummy start on the same node, advance independently, and second.Next = second.Next.Next drops the target with a plain pointer reassignment, no ownership dance like Rust's. The composite literal &ListNode{Next: head} builds the dummy in a single expression, and listToSlice grows a var res []int nil slice via append, so an empty list yields nil rather than an allocated empty slice.
Comments (0)
Stub — comments live in your browser only (localStorage). No server round-trip yet.
No comments yet. Be the first.