My c++ simple recursion solution, O(n) time


  • 0
    B
    class Solution {
    public:
        ListNode *deleteDuplicates(ListNode *head) {
            if ( head == NULL )
                return NULL;
            if ( head->next == NULL )
                return head;
            ListNode *p=head->next;
            while( p->val == head->val){   
                p = p->next;    //find first value that is different from head value;
                if ( p == NULL )
                    break;
            }
            if ( p == NULL )     //if all value is same, return NULL;
                return NULL;
            if ( p == head->next ) {  //if the second value is different from head value;
                head->next = deleteDuplicates(p);
                return head;
            }
            else    // return the head from p;
                return deleteDuplicates(p);
        }
    };

  • 0

    O(n^2) time.


Log in to reply
 

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