369. Plus One Linked List

Given a non-negative integer represented asnon-emptya singly linked list of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

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
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode plusOne(ListNode head) {
        if (head == null) return head;
        ListNode newHead = reverse(head);
        newHead = addOne(newHead);

        return reverse(newHead);
    }

    private ListNode addOne(ListNode head){
        int addOn = 1;

        ListNode ans = head;
        while (head != null){
            int sum = addOn + head.val;
            head.val = sum % 10;
            if (sum < 10) break;
            addOn = sum / 10;

            if (head.next != null){
                head = head.next;
            }
            else if (addOn > 0){
                head.next = new ListNode(addOn);
                break;
            }
        }

        return ans;
    }

    private ListNode reverse(ListNode head){
        ListNode prev = null;

        while (head != null){
            ListNode next = head.next;
            head.next = prev;
            prev = head;
            head = next;
        }

        return prev;
    }
}

results for ""

    No results matching ""