C++ recursive solution, easy understand


  • 1
     ListNode* plusOne(ListNode* head) {
        if (!head) return nullptr;
        int carry = 0;
        helper(head, carry);
        if (carry > 0){ 
            ListNode* newHead = new ListNode(carry);
            newHead->next = head;
            return newHead;
        }
        return head;
     }
    
     void helper(ListNode* node, int& carry){
        if (!node->next){
            int val = node->val + 1;
            node->val = val%10;
            carry = val/10;
            return;            
        }
        helper(node->next, carry);
        if (carry>0){
            int temp = node->val + carry;
            node->val = temp%10;
            carry = temp/10;
        }
     }

Log in to reply
 

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