albertonline· portal
blind75

Remove Nth Node From End of List: Manipulating Linked Lists

Jan 7, 2024 · Solving the Remove Nth Node From End of List problem by efficiently identifying and removing a specific node from a singly linked list.

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

javascript

Breaking Down the Solution


  • Initialize Two Pointers: Use two pointers, first and second, both starting from a dummy node before the head.
  • Advance the First Pointer: Move first n+1 steps ahead, creating a gap of n nodes between first and second.
  • Move Both Pointers: Traverse the list with both pointers until first reaches the end. At this point, second is just before the nth node from the end.
  • Remove the Nth Node: Adjust the next pointer of the second node 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

rust

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

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.