LC 82. Remove Duplicates from Sorted List II

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(!head || !head->next)
            return head;
        ListNode* p = head;
        ListNode* q = head->next;
        vector<int> dup;
        while(q){
            if(p->val == q->val){
                q = q->next;
                dup.push_back(p->val);
                continue;
            }
            p->next = q;
            p = q;
            q = p->next;
        }
        for(int i=0;i<dup.size();i++)
            cout << dup[i] << " ";
        while(head && find(dup.begin(),dup.end(),head->val)!=dup.end())
            head = head->next;
        if(!head || !head->next)
            return head;
        p = head;
        q = head->next;
        bool check = false;
        while(q){
            while(q && find(dup.begin(),dup.end(),q->val)!=dup.end()){
                q = q->next;
                check = true;
            }
            if(check){
                p->next = q;
                check = false;
                continue;
            }
            p = q;
            q = p->next;
        }
            
        return head;
    }
};


Dicussion Forum