1. 程式人生 > 其它 >Remove Nth Node From End of List

Remove Nth Node From End of List

Source

Given a linked list, remove the nth node from the end of list and return its head.

Note
The minimum number of nodes in list is n.

Example
Given linked list: 1->2->3->4->5->null, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5
->null. Challenge O(n) time

題解

簡單題,使用快慢指標解決此題,需要注意最後刪除的是否為頭節點。讓快指標先走n步,直至快指標走到終點,找到需要刪除節點之前的一個節點,改變node->next域即可。

C++

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 
*/ class Solution { public: /** * @param head: The first node of linked list. * @param n: An integer. * @return: The head of linked list. */ ListNode *removeNthFromEnd(ListNode *head, int n) { if (NULL == head || n < 1) { return NULL; } ListNode
*dummy = new ListNode(0); dummy->next = head; ListNode *preDel = dummy; for (int i = 0; i != n; ++i) { if (NULL == head) { return NULL; } head = head->next; } while (head) { head = head->next; preDel = preDel->next; } preDel->next = preDel->next->next; return dummy->next; } };

Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == nul) return head;

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode fast = head;
        ListNode slow = dummy;
        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }

        while(fast != null) {
            fast = fast.next;
            slow = slow.next;
        }

        // gc friendly
        // ListNode toBeDeleted = slow.next;
        slow.next = slow.next.next;
        // toBeDeleted.next = null;
        // toBeDeleted = null;

        return dummy.next;
    }
}

原始碼分析

引入dummy節點後畫個圖分析下就能確定head和preDel的轉移關係了。 注意 while 迴圈中和快慢指標初始化的關係,否則容易在順序上錯一。

複雜度分析

極限情況下遍歷兩遍連結串列,時間複雜度為 O(n).