Recursive Solution done by pre-appending zero


  • 0
    public ListNode plusOne(ListNode list) {
        ListNode head = new ListNode(0);
        ListNode zero = new ListNode(0);
        head.next = zero;
        zero.next = list;
        
        search(head.next);
        if (head.next.val == 0) {
            return head.next.next;
        } else {
            return head.next;
        }
    }
    
    boolean search(ListNode node) {
        if (node == null) return false;
        if (search(node.next)) return true;
        
        if (node.val == 9) {
            node.val = 0;
            return false;
        } else if (node.val < 9) { 
            node.val++;
            return true;
        }
        
        return false;
    }

Log in to reply
 

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