C++ solution with memory deallocation


  • 0
    S
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            if(!head) return NULL;
            if(!head->next) return head;
            
            ListNode *p = head, *c = head->next, *n = NULL, *t = head;
            bool flag = false;
            while(c){
                if(p->val == c->val){
                    flag = true;
                    c = c->next;
                }
                else{
                    if(flag){
                        while(p!=c){
                            ListNode* x = p;
                            p = p->next;
                            delete x;
                        }
                        if(n) n->next = c;
                        else head = p;
                        flag = false;
                    }
                    else{
                        n = p;
                        p = c;
                    }
                    c = c->next;
                }
            }
            
            if(flag){
                while(p!=c){
                    ListNode* x = p;
                    p = p->next;
                    delete x;
                }
                flag = false;
            }
            if(n && !p) n->next = c;
            else if(n && p) head = head;
            else head = p;
            return head;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.