Remove Nth Node From End of List
Unlink the node that sits n places from the end of a linked list, walking the list only once.
Given the first node (the headnn
Example 1
Output: [1, 2, 3, 5]
Example 2
Output: []
Example 3
Output: [2]
Explanation: the head itself is removed.
The Idea
A linked list is like a treasure hunt. Each clue tells you where the next one is, and you only learn the way by following the clues one at a time. In a linked list, each item is a node that holds a value and a nextnextnull
Take Example 1, the list 1, 2, 3, 4, 5 with n = 2next
That raises the real question. Standing at the head, how do we know that 3 is the one, without first walking to the end to count the nodes? A node cannot tell how far it is from the end.
Two markers walking the list can tell. Call them leadtrailleadleadtrail
Both rows start with an extra node labelled dummy, placed in front of 1, so that even the head has a node before it. In the row labelled "After lead moves n + 1 = 3 steps", trailleadleadnulltrailtrail.next
So the distance from the end is measured by the gap between two markers, not by counting the list first. A pair of markers moving through the same list like this is often called the two-pointer technique.
Solution Approach
Turning that idea into code means comparing it with the slower way of counting first, then settling three things: what to do when the head itself is removed, how big the gap must be, and how to unlink the node.
The two-pass way
Why not count the nodes first? Walk the whole list once to get its length L, then walk again L - n steps to the node before the one to remove. That works, but it reads the list twice. The two markers do the counting while they walk, so the list is read once.
A dummy node in front of the head
What if the node to remove is the head? In Example 3, the list is 1, 2 and n = 2nextdummy.next
The size of the gap
How far ahead should leadleadnullnullleadtrail
Unlinking the node
Once trailtrail.nexttrail.next.nextnulltrail.next = trail.next.next
Java Solution
The method removeNthFromEnd
- First, create the dummy node with
, so it points at the head, and start both markers,new ListNode(0, head) andlead , on it.trail - Move
forward n + 1 times with alead loop whose counterfor starts at 0 and runs whilei .i <= n - Then a
loop moveswhile andlead one node each, untiltrail islead .null - Now
is just before the node to remove, so settrail .trail.next = trail.next.next - Return
, the head of the changed list.dummy.next
The class also has a small ListNodebuildshowmainn = 1n = 5
public class RemoveNthNodeFromEndOfList {
static class ListNode {
int val;
ListNode next;
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head); // a node in front of the head
ListNode lead = dummy;
ListNode trail = dummy;
for (int i = 0; i <= n; i++) {
lead = lead.next; // n + 1 steps: lead is n + 1 nodes ahead
}
while (lead != null) {
lead = lead.next;
trail = trail.next;
}
trail.next = trail.next.next; // trail is just before the node to remove
return dummy.next;
}
static ListNode build(int... values) {
ListNode head = null;
for (int i = values.length - 1; i >= 0; i--) {
head = new ListNode(values[i], head);
}
return head;
}
static String show(ListNode head) {
StringBuilder sb = new StringBuilder("[");
for (ListNode node = head; node != null; node = node.next) {
sb.append(node.val).append(node.next != null ? ", " : "");
}
return sb.append("]").toString();
}
public static void main(String[] args) {
System.out.println(show(removeNthFromEnd(build(1, 2, 3, 4, 5), 2)));
System.out.println(show(removeNthFromEnd(build(1), 1)));
System.out.println(show(removeNthFromEnd(build(1, 2), 2)));
System.out.println(show(removeNthFromEnd(build(1, 2), 1)));
System.out.println(show(removeNthFromEnd(build(1, 2, 3, 4, 5), 5)));
}
}
Running it prints:
[1, 2, 3, 5]
[]
[2]
[1]
[2, 3, 4, 5]
Node 4 is gone from [1, 2, 3, 5][][2][1]trailtrail.next.nextnull
Look at the last line, [2, 3, 4, 5]n = 5leadnullwhiletrail
The <=i < ntrail[1, 2, 3, 4]NullPointerExceptiontrail.nextnull
Complexity
The work is one walk of leadtrail
- Time: O(L), where L is the number of nodes. Across its two loops,
steps over each node once and then ontolead , andnull takes fewer steps than that.trail - Space: O(1). However long the list is, the method adds only the dummy node and the two markers.