C++ Recursive Solution


  • 0
    L
        void plusOneAux(ListNode* head, bool & flag) {
            if (!head) return;
            plusOneAux(head->next, flag);
            if (flag) {
                if (head->val + 1 == 10) head->val = 0;
                else {
                    head->val++;
                    flag = false;
                }
            }
        }
        ListNode* plusOne(ListNode* head) {
            if (!head) return NULL;
            bool flag = true;
            plusOneAux(head, flag);
            if (head->val == 0) { // overflow
                ListNode *one = new ListNode(1);
                ListNode *temp = head;
                one->next = temp;
                head = one;
            }
            return head;
        }
    

Log in to reply
 

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