1. 程式人生 > >Remove Nth Node From End of List(從連結串列表尾刪除第n個節點)

Remove Nth Node From End of List(從連結串列表尾刪除第n個節點)

題目:

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。

分析:

  1. 我看過大多數人的思路是先求出總的連結串列長度,然後再進行m-n次迴圈找到待要刪除的節點。
  2. 大神的一次遍歷便搞定的演算法,非常優美。直接貼大神的程式碼。
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;
    }
};