Java Recursive Solution - Beats 70% submissions


  • 0
    G
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode plusOne(ListNode head) {
            int carry = helper(head);
            if(carry == 1){
                ListNode newHead = new ListNode(1);
                newHead.next = head;
                return newHead;
            }
            return head;
        }
        
        private int helper(ListNode head){
            if(head.next != null ){
                int carry = helper(head.next);
                if (carry==0){
                    return 0;
                }
            }
            //head.val++; //not needed if we check for value 9
            if(head.val==9){
                head.val = 0;
                return 1;
            } else {
                head.val++;
                return 0;
            }
        }
    }
    

Log in to reply
 

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