The question is to remove the nth node from the end of a linked list.
Solution:
One solution is to use two pointers. The idea is to keep two pointers with a distance n between them. When one pointer reach the end, the other pointer is the parent of the node we are to remove.
One example is to remove the 2nd node from the end of a linked list [1,2,3,4,5], which here is 4.
step1: first keep two pointers,p1, p2, initially at the head: 1(p1, p2), 2, 3, 4, 5.
step2: We want to keep a distance of 2 between them. So now we move p2 2 steps further, and it becomes: 1(p1), 2, 3(p2), 4, 5.
step3: Now we iterate, and each iteration moves p1 and p2 1 step toward the end. Iterations stop when p2 reach the end( see if p2->next == NULL. If so then p2 now is the end):
iteration 1: 1, 2(p1), 3, 4(p2), 5
iteration 2: 1, 2, 3(p1), 4, 5(p2)
p2 is at the end and we stop.
step4: Now p1 is the parent of the node, 4, we are to remove. Thus we make p1->next = p1->next-next;
One trouble for this question is the boundary problem: the head is the one we want to remove. In this case we cannot use p1->next = p1->next->next. One thing we can see in this case is that if the head is the one we want to remove, or n == length of the linked list, p2 would reach the end in step 2. Otherwise p2 would not reach the end. Thus in step 2 we add one condition to check if p2 reaches the end. If so we just remove the head, and return head->next.
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *p1 = head;
ListNode *p2 = head;
while(n > 0){
if(p2->next == NULL){
return head->next;
}
p2 = p2->next;
n--;
}
while(p2->next != NULL){
p2 = p2->next;
p1 = p1->next;
}
p1->next = p1->next->next;
return head;
}
};