力扣 19 刪除鏈表的倒數第N個節點

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode * first=head ,*second = head;
        if(head == NULL || head == NULL)  return NULL;
        for(int i=0;i<n;i++)
            first = first->next;
        if(first == NULL)
            return head->next;
        while(first->next){
            first = first->next;
            second = second->next;
        }
        second->next = second->next->next;
        return head;
    }

};

這道題就是採用雙指針,兩個指針之間差N個,second是第倒數N+1個指針,並且要注意到刪除頭節點的情況。

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