Simple easy understand recursive solution


  • 0
    Z
    public ListNode plusOne(ListNode head) {
        if (head == null) return null;
        
        int[] flag = new int[]{0};
        ListNode node = plusOneHelper(head, flag);
    
        if (flag[0] == 1) {
        	ListNode newHead = new ListNode(1);
        	newHead.next = node;
        	node = newHead;
        }
        
        return node;
    }
    
    public ListNode plusOneHelper(ListNode head, int[] flag) {
    	if (head == null) return null;
    	
    	ListNode next = plusOneHelper(head.next, flag);
    	
    	if (next == null) {
    		// current node is the end node
    		int sum = head.val + 1;
    		flag[0] = sum / 10;
    		head.val = sum % 10;;
    	}
    	
    	if (next != null && flag[0] == 1) {
    		int sum = head.val + 1;
    		flag[0] = sum / 10;
    		head.val = sum % 10;
    	}
    	
    	return head;
    }

Log in to reply
 

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