[LeetCode] 19. 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.

 

這道題讓我們移除鏈表倒數第N個節點,限定n一定是有效的,即n不會大於鏈表中的元素總數。還有題目要求一次遍歷解決問題,那么就得想些比較巧妙的方法了。比如首先要考慮的時,如何找到倒數第N個節點,由於只允許一次遍歷,所以不能用一次完整的遍歷來統計鏈表中元素的個數,而是遍歷到對應位置就應該移除了。那么就需要用兩個指針來幫助解題,pre 和 cur 指針。首先 cur 指針先向前走N步,如果此時 cur 指向空,說明N為鏈表的長度,則需要移除的為首元素,那么此時返回 head->next 即可,如果 cur 存在,再繼續往下走,此時 pre 指針也跟着走,直到 cur 為最后一個元素時停止,此時 pre 指向要移除元素的前一個元素,再修改指針跳過需要移除的元素即可,參見代碼如下:

 

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (!head->next) return NULL;
        ListNode *pre = head, *cur = head;
        for (int i = 0; i < n; ++i) cur = cur->next;
        if (!cur) return head->next;
        while (cur->next) {
            cur = cur->next;
            pre = pre->next;
        }
        pre->next = pre->next->next;
        return head;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/19

 

類似題目:

Linked List Cycle

Linked List Cycle II

 

參考資料:

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

https://leetcode.com/problems/remove-nth-node-from-end-of-list/discuss/8812/My-short-C%2B%2B-solution

https://leetcode.com/problems/remove-nth-node-from-end-of-list/discuss/8804/Simple-Java-solution-in-one-pass

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM