您的位置:首页 > Web前端 > Node.js

[LeetCode]—Remove Nth Node From End of List 删除链表的倒数第n个节点

2014-06-30 17:06 267 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐