Given a non-negative number represented as a singly linked list of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

Example:
Input:
1->2->3

Output:
1->2->4

Solution

/**
 * 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) {
        if(helper(head)) {
            ListNode newHead = new ListNode(1);
            newHead.next = head;
            return newHead;
        } else {
            return head;
        }
    }

    public boolean helper(ListNode node) {
        boolean carry = false;
        if(node.next == null || helper(node.next)) {
            node.val++;
            carry = node.val >= 10;
            node.val %= 10;
        }
        return carry;
    }
}

results matching ""

    No results matching ""