Java Recursion Solution Easy to Understand


  • 0
    Y
    /**
     * 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 == 0) return head;
            else {
                ListNode h = new ListNode(1);
                h.next = head;
                return h;
            }
        }
        
        private int helper(ListNode cur) {
            if (cur == null) {
                return 1;
            } else {
                int carry = helper(cur.next);
                int ret = (carry + cur.val) / 10;
                cur.val = (carry + cur.val) % 10;
                return ret;
            }
        }
    }
    

Log in to reply
 

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