Compact C++ solution


  • 1
    K
    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            if (!head)
                return NULL;
            
            ListNode dummy(0);
            ListNode* ptr = &dummy;
            int pre_val = head->val - 1; // sentinal
            while (head) {
                ListNode* next_head = head->next;
                int next_pre_val = head->val;
                if (
                    pre_val != head->val && 
                    (!head->next || head->val != head->next->val)
                ) {
                    ptr->next = head;
                    ptr = head;
                    ptr->next = NULL;
                } else {
                    delete head;
                }
                pre_val = next_pre_val;
                head = next_head;
            }
            return dummy.next;
        }
    };

Log in to reply
 

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