Java Solution using recursion


  • 0
    public ListNode plusOne(ListNode head) {
        ListNode dummy = new ListNode(0);
        if(plusOneHelper(head, dummy)) {
            return dummy.next;
        } else {
            dummy.val = 1;
            return dummy;
        }
    }
    
    // true: don't change; false: +1;
    public boolean plusOneHelper(ListNode raw, ListNode newHead) {
        if(raw == null) return false;
        newHead.next = new ListNode(raw.val);
        boolean res = plusOneHelper(raw.next, newHead.next);
        if(res) {
            return res;
        } else {
            if(newHead.next.val == 9) {
                newHead.next.val = 0;
                return false;
            } else {
                newHead.next.val += 1;
                return true;
            }
        }
    }

Log in to reply
 

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