leetcode19 刪除鏈表的倒數第N個節點

struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x): val(x), next(NULL
};

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if((head->next == nullptr) && (n==1))
            return nullptr;
        ListNode *q = head;
        ListNode *p = head;
        int count = 0;
        while(count<n && p){
            p = p->next;
            count += 1;
        }
        
        if(!p)
            return head->next;//着重注意p指針不存在的情況
        
        while(p->next){
            q = q->next;
            p = p->next;
        }
        q->next = q->next->next;
        
        return head;
           
    }
};

 

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