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个节点的位置?
办法:用两个指针p,q。让p指针先前进n步。再让p,q同步前移。这样就形成了一个跨度为n的“刻度尺”。就能方便找出倒数第n个节点。
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
ListNode *p=head,*q=head;
while(n--){
p=p->next;
} //此时p与q已经相差n步
if(p==NULL){ //表示要删的头结点,n与链表的长度一样长
head=head->next;
return head;
}
while(p->next!=NULL){
p=p->next;
q=q->next;
} //次时q->next 就是需要被删除的节点
q->next=q->next->next;
return head;
}
};