Algo-Sim › Linked Lists
Remove Nth Node From End of List
Medium · Linked Lists · step through it in Java, Python and C++ on your own input
Remove the nth node from the end in one pass: open a gap of n between two pointers, then slide both until fast hits the tail.
Problem
Given the head of a linked list and n, remove the nth node counted from the end (the last node is 1st) and return the head of the resulting list.
Constraints
- 1 ≤ number of nodes ≤ 30
- 0 ≤ Node.val ≤ 100
- 1 ≤ n ≤ number of nodes
- Follow-up: one pass
Edge cases to test
- Remove the head (n = length)
- One node
- Remove the tail
Follow-up questions
- Why use a dummy node?
- Removing the head would otherwise need a special case; the dummy gives every node a predecessor.
- Two passes or one?
- Counting the length first is also O(n); the gap trick finds the node in one pass.
Solution
Java
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode fast = dummy, slow = dummy;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}Python
def remove_nth_from_end(head, n):
dummy = ListNode(0, head)
fast = slow = dummy
for _ in range(n):
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.nextC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
ListNode *dummy = new ListNode(0, head);
ListNode *fast = dummy, *slow = dummy;
for (int i = 0; i < n; i++) {
fast = fast->next;
}
while (fast->next != nullptr) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummy->next;
}
};
More Linked Lists problems
- Reverse Linked List (Easy)
- Reverse Linked List (Recursive) (Easy)
- Merge Two Sorted Lists (Easy)
- Middle of the Linked List (Easy)
- Palindrome Linked List (Easy)
- Linked List Cycle (Easy)
- Linked List Cycle II (Medium)
- Intersection of Two Linked Lists (Easy)
- Find the Duplicate Number (Medium)
- Reorder List (Medium)
- Sort List (Medium)
- Add Two Numbers (Medium)
- Copy List with Random Pointer (Medium)
- Reverse Nodes in k-Group (Hard)