Java recursive solution


  • 0
    G
    public ListNode plusOne(ListNode head) {
        boolean carry = addOne(head);
        if(carry) {
            ListNode first = new ListNode(1);
            first.next = head;
            head = first;
        }
        return head;
    }
    
    public boolean addOne(ListNode head) { 
        if(head == null) return true; 
        boolean carry = addOne(head.next);
        if(head.val == 9 && carry) {
            head.val = 0;
            return true;
        } else if(carry) {
            head.val += 1;
        }
        return false;
    }

Log in to reply
 

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