Recursive solution with helper function


  • 0
    J
    /**
     * 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) {
            ListNode newHead = new ListNode(0);
            newHead.next = head;
            if (helper(newHead).val > 0) {
                return newHead;
            } else {
                return head;
            }
        }
        private ListNode helper(ListNode head) {
            if (head == null) {
                return head;
            }
            
            if (head.next == null) {
                head.val ++;
            } else if (helper(head.next).val > 9) {
                head.val ++;
                head.next.val -= 10;
            }
            
            return head;
        }
    }

Log in to reply
 

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