Share my solution: three pointers: ptr, prev, next.


  • 0
    Y

    class Solution {
    public:
    ListNode *deleteDuplicates(ListNode *head) {
    if (head == NULL)
    return head;

        ListNode* ptr = head;
        ListNode* prev = NULL;
        ListNode* next = NULL;
        
        while (ptr)
        {
            if (ptr->next == NULL)
                break;
                
            next = ptr->next;
            
            while (next && ptr->val == next->val)
            {
                ListNode* tmp = next;        
                next = next->next;
                delete tmp;
            }
            
            if (next == ptr->next)
            {
                prev = ptr;
                ptr = ptr->next;
                continue;
            }
            
            if (prev == NULL)
            {
                head = next;
                delete ptr;
                ptr = next;
            }
            else
            {
                prev->next = next;
                delete ptr;
                ptr = next;
            }
        }
        
        return head;
            
    }
    

    };


Log in to reply
 

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