Why my solution in C++ have a wrong answer


  • 0
    S
    class Solution {
    
    public:
        ListNode *deleteDuplicates(ListNode *head) {
            if(!head) return head;
            
            ListNode* dummy = (ListNode*)malloc(sizeof(ListNode));
            
            dummy->next = head;
            
            recur(dummy, head);
            return dummy->next;
        }
    private:
        static void recur(ListNode *prev, ListNode *cur){
            if(cur == nullptr) return ;
            
            if(prev->val == cur->val) {
                prev->next = cur->next;
                delete cur;
                recur(prev, prev->next);
            }else {
                recur(prev->next, cur->next);
            }      
        }
    };

  • 0
    K

    I did a little change in your code and It get accepted. The reason is when you call recur method, in that method you modified dummy->next. So now dummy->next might not pointing to head.

    class Solution {
    public:
        ListNode *deleteDuplicates(ListNode *head) {
            if(!head) return head;
    
            ListNode* dummy = (ListNode*)malloc(sizeof(ListNode));
    
            dummy->next = head;
    
            recur(head, head->next);
            return head;
        }
    private:
        static void recur(ListNode* prev, ListNode* cur){
            if(cur == nullptr) return ;
    
            if(prev->val == cur->val) {
                prev->next = cur->next;
                delete cur;
                recur(prev, prev->next);
            }else {
                recur(prev->next, cur->next);
            }      
        }
    

    };


Log in to reply
 

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