12ms C++ code with 3 pointers


  • 0
    J
    ListNode* deleteDuplicates2(ListNode* head) {
        if(!head || !head->next) return head;
        ListNode* preHead = new ListNode(0);
        ListNode* mark = preHead;
        preHead->next = head;
        if(head->val!=head->next->val) mark = head;
        ListNode* p = head;
        while (p->next->next) {
            if(p->val==p->next->val || p->next->val==p->next->next->val)
                p = p->next;
            else {
                mark->next = p->next;
                p = p->next;
                mark = mark->next;
            }
        }
        if(p->val == p->next->val) mark->next = NULL;
        else mark->next = p->next;
        return preHead->next;
    }

  • 1
    C

    Here is my code using recursive

     class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            if(head == NULL) return NULL;
            ListNode* next = head->next;
            bool flag = false;
            while(next != NULL && next->val == head->val)
            {
                next = next->next;
                flag = true;
            }
            if(flag)
            {
                head = next;
                return deleteDuplicates(head);
            }
            else
            {
                head->next = deleteDuplicates(head->next);
                return head;
            }
        }
    };

Log in to reply
 

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