C++ iterative solution


  • 0
    G
    class Solution {
    public:
        
        ListNode* deleteDuplicates(ListNode* head) {
            
            if(head == nullptr || head->next == nullptr){
                return head;
            }
            
            ListNode *prev = head;
            ListNode *next = head->next;
            ListNode *nHead = nullptr;
            ListNode *nextHead = nullptr;
            
            while(next != nullptr){
                while(next != nullptr && next->val == prev->val){
                    next = next->next;
                }
                
                if(prev->next == next){
                    if(!nHead){
                        nHead = prev;
                        nextHead = nHead;
                    }
                    else{
                        nextHead->next = prev;
                        nextHead = prev;
                    }
                }
                
                prev = next;
                if(next != nullptr){
                    next = next->next;
                }
            }
            
            if(nextHead){
                nextHead->next = prev;
            }
            else{
                nHead = prev;
            }
            
            return nHead;
        }
    };
    

Log in to reply
 

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