8 ms C++ solution


  • 0
    L
    ListNode* deleteDuplicates(ListNode* head) {
            if (head == NULL || head->next == NULL)
                return head;
            
            ListNode *newHead = head;
            ListNode *pPreNode = NULL;
            ListNode *pNode = head;
            
            while (pNode != NULL)
            {
                ListNode *pNext = pNode->next;
                bool needDelete = false;
                if (pNext != NULL && pNext->val == pNode->val)
                    needDelete = true;
                
                if (!needDelete)
                {
                    pPreNode = pNode;
                    pNode = pNext;
                }
                else
                {
                    int val = pNode->val;
                    ListNode *pToBeDelete = pNode;
                    while (pToBeDelete != NULL && pToBeDelete->val == val)
                    {
                        pNext = pToBeDelete->next;
                        delete pToBeDelete;
                        pToBeDelete = pNext;
                    }
                    
                    if (pPreNode == NULL)
                        newHead = pNext;
                    else
                        pPreNode->next = pNext;
                    pNode = pNext;
                }
            }
            
            return newHead;
        }

Log in to reply
 

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