C++ 12ms 2 simple solutions


  • 0
    Z
    class Solution {
    public:
    ListNode* deleteDuplicates(ListNode* head) {
        //return solution1(head);     //iterative
        return solution2(head);   //recursive
    }
    private:
    ListNode* solution1(ListNode* head) {
        if(head == NULL || head->next == NULL) return head;
        ListNode *cur = head, *tmp = cur->next;
        while(tmp){
            if(cur->val == tmp->val){
                cur->next = tmp->next;
                delete tmp;
            }else cur = tmp;
            tmp = cur->next;
        }
        return head;
    }
    ListNode *solution2(ListNode *head){
        if(head == NULL || head->next == NULL) return head;
        ListNode *tmp = solution2(head->next);
        if(head->val == tmp->val){
            head->next = tmp->next;
            delete tmp;
        }
        return head;
    }
    };

Log in to reply
 

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