Remove Nth Node from End of List
Given A linked list, remove the nth node from the end of the list and return its head.
For example,
Given linked list:1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass. Analysis
It can only be traversed once, so the length of the linked list cannot be counted first. You can use two pointers, one pointer to n steps, and two pointers to the remaining n-k steps at the same time. Source 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 dummy (-1);
Dummy.next = head;
ListNode *p = &dummy, *q = &dummy;
Q Go first n steps for (int i = 0; i < n; i++) {q = q->next;
}//Two pointers along while (q->next) {q = q->next;
p = p->next;
} ListNode *tmp = p->next;
P->next = p->next->next;
Delete tmp;
return dummy.next; }
};