My C++ solution with a newHead, 17ms


  • 0
    T

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

        ListNode *newHead = new ListNode(0);
        newHead->next = head;
        
        ListNode *p = newHead;  // previous
        ListNode *c = p->next;  // current
        
        while (c->next != NULL) { 
            if (c->val != c->next->val) { 
                if (p->next == c) { // 1, 2, 3, 4, 5
                    p = c;
                } else {
                    p->next = c->next; // 1, 2, 3, 3, 3, 4
                }
            }
            
            c = c->next;
        }
        
        if (p->next != c)
            p->next = c->next;
    
        
        return  newHead->next;
    }
    

    };


  • 0
    Z
    ListNode *deleteDuplicates1(ListNode *head) {
        ListNode *list = NULL;
        ListNode **p_list = &list;
        int val = head ? head->val - 1 : 0;
        while (head) {
            if ((head->val == val) || (head->next && head->val == head->next->val)) {
                val = head->val;
                ListNode* tmp = head;
                head = head->next;
                delete tmp;
            } else {
                *p_list = head;
                p_list = &head->next;
                val = head->val - 1;
                head = head->next;
            }
        }
        *p_list = NULL;
        return list;
    }

Log in to reply
 

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