ZhongKuo0228 / study

0 stars 0 forks source link

19. Remove Nth Node From End of List #53

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago

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

fockspaces commented 1 year ago
  1. 用快慢指針,快指針提前慢指針走 n 個節點,之後兩者同速前進,當 fast 到最後一個節點時,slow 即為從最後數來第 N 個 node
  2. 這邊要考慮 edge case:刪掉的 node 為 head,當 fast 在提前走時碰到 NULL,代表要刪的是頭,這邊直接 return head->next
    /**
    * Definition for singly-linked list.
    * struct ListNode {
    *     int val;
    *     ListNode *next;
    *     ListNode() : val(0), next(nullptr) {}
    *     ListNode(int x) : val(x), next(nullptr) {}
    *     ListNode(int x, ListNode *next) : val(x), next(next) {}
    * };
    */
    class Solution {
    public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *slow = head, *fast = head;
        while(n--) fast = fast->next;
        if(!fast) return head->next;
        while(fast && fast->next) 
            {fast = fast->next; slow = slow->next;}
        slow->next = slow->next ? slow->next->next : NULL;
        return head;
    }
    };