[LeetCode] 19. Remove Nth Node From End of List

这题有几个关键的点

  • 建立哨兵(sentinel)节点便于返回链表头
  • 快慢指针:当快指针指向倒数第1个节点,慢指针必然指向倒数第1 + N个节点
  • 节点是被new出来的,C++中需要手动释放(delete)这个节点的内存
/**
 * 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;
    }
};

你可能感兴趣的:([LeetCode] 19. Remove Nth Node From End of List)