C++ recursive solution beats 100%


  • 0
    A
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* plusOne(ListNode* head) {
            int carry = plusOneHelper(head);
            if (carry > 0) {
                ListNode* newHead = new ListNode(carry);
                newHead->next = head;
                head = newHead;
            }
            return head;
        }
    private:
        int plusOneHelper(ListNode* head) {
            if (head == NULL)   {return NULL;}
            int carry = head->next == NULL ? 1 : plusOneHelper(head->next);
            if (carry > 0 ) {
                carry += head->val;
                head->val = carry % 10;
            }
            return carry / 10;
        }
    };
    

Log in to reply
 

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