Linked List

[LeetCode] 19. Remove Nth Node F

2019-09-26  本文已影响0人  hugo54

这题有几个关键的点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    // if n = 2 
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        // sentinel  ->  1  ->  2  ->  3  ->  4  ->  5  ->  6  ->
        //   slow
        //   fast
        ListNode* sentinel = new ListNode(0);
        sentinel->next = head;
        ListNode* slow = sentinel;
        ListNode* fast = sentinel;
        
        // sentinel  ->  1  ->  2  ->  3  ->  4  ->  5  ->  6  ->
        //   slow              fast
        //
        // Find Nth from end <-> fast is N steps faster than slow
        for (int i = 1; i <= n; i++) {
            fast = fast->next;
        }
        
        // sentinel  ->  1  ->  2  ->  3  ->  4  ->  5  ->  6  ->
        //                                   slow          fast
        while (fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next;
        }

        // sentinel  ->  1  ->  2  ->  3  ->  4   ->  6  ->
        //                                   slow    fast
        ListNode* temp = slow->next;
        slow->next = slow->next->next;
        delete temp;
        return sentinel->next;
    }
};

上一篇 下一篇

猜你喜欢

热点阅读