题目:
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;
}
};