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

Remove Nth Node From End of List(从链表表尾删除第n个节点)

2014-12-26 21:44 375 查看

题目:

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(试着在一次遍历中完成).

环境:

题目来源于leetcode,测试通过leetcode。

分析:

我看过大多数人的思路是先求出总的链表长度,然后再进行m-n次循环找到待要删除的节点。
大神的一次遍历便搞定的算法,非常优美。直接贴大神的代码。

class Solution
{
public:
ListNode* removeNthFromEnd(ListNode* head, int n)
{
ListNode** t1 = &head, *t2 = head;
for(int i = 1; i < n; ++i)
{
t2 = t2->next;
}
while(t2->next != NULL)
{
t1 = &((*t1)->next);
t2 = t2->next;
}
*t1 = (*t1)->next;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 C++
相关文章推荐