Straightfoward C++ recursive and iterative solution


  • 3

    Iterative

      ListNode* deleteDuplicates(ListNode* head) {
            ListNode * temp = head;
            while(temp){
                while(temp->next && temp->val == temp->next->val)
                        temp->next = temp->next->next;
                temp = temp->next;
            }
            return head;
        }
    
    1. Recursive
        ListNode* deleteDuplicates(ListNode* head) {
            helper(head);
            return head;
        }
        
        void helper(ListNode* head){
            if (!head || !head->next) return ;
            while (head->val == head->next->val) {
                head->next = head->next->next;
                if(!head->next) return;
            }
            helper(head->next);
        }
    

Log in to reply
 

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