leetcode (19) - Remove Nth Node From End of List

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
        if(head == NULL || n <= 0)
            return head;
        
        struct ListNode* first = head;
        struct ListNode* second = head;
        struct ListNode* pre = NULL;
        
        for(int i = 0; i < n - 1; i++) // 中間間隔N-1的距離
            first = first->next;
            
        while(first->next)
        {
            pre = second;  // pre是倒數第k個節點的前一個節點,用來刪除
            second = second->next;  // second是倒數第k個節點
            first = first->next;
        }
        
        if( !pre )  // 如果倒數第k個節點就是head,那麼pre會保留原來的NULL,這時head直接是倒數第k個節點second的下一個節點
            head = second->next;
        else
            pre->next = second->next;
        
        return head;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章