19. Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of 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 will always be valid.
Try to do this in one pass.
分析
只能遍历一遍,所以不能先统计出链表的长度了。可以使用两个指针,一个指针先走n步,然后两个指针同时走剩下的n-k步。
源码
/**
* 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先走n步
for(int i = 0; i < n; i++) {
q = q->next;
}
// 两个指针一起走
while(q->next) {
q = q->next;
p = p->next;
}
ListNode *tmp = p->next;
p->next = p->next->next;
delete tmp;
return dummy.next;
}
};