leetcode 19: 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.

思路:

題目看來挺簡單,主要就是設置一個前行節點一個後行節點,同步控制兩節點距離一直到鏈表末端。但是實踐完成代碼的思路上還是有一點點技巧和注意的。
這裏我用了一個鏈表附加頭節點,這樣在刪除頭結點問題上可以很方便解決;然後注意要得到的節點應該是所要求刪除節點的前一個節點;還有就是最後返回鏈表時,要返回更新後的head節點,因爲head可能有改變。

代碼:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* prehead = new ListNode(-1);
        prehead->next = head;
        ListNode* bias = prehead;
        ListNode* targetpre = prehead;
        //bias move forward n steps
        for(int i = 0; i < n; i++)  
        {
            if(bias == NULL) return head;
            bias = bias->next;   
        }
        //bias point to the end, at the same time, target point to the previous node of the nth from the end.
        while(bias->next != NULL)
        {
            bias = bias->next;
            targetpre = targetpre->next;
        }

        ListNode* temp = targetpre->next;
        targetpre->next = temp->next;
        head = prehead->next;   //update the new head
        delete temp;
        delete prehead;
        return head;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章