Plus One Linked List

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

Tips:

Reverse, +1, Reverse

Code:

/**
 * 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 (head == null) {
            return head;
        }
        head = reverse(head);
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode result = dummy;
        int carry = 1;
        while (result.next != null) {
            result = result.next;
            int sum = result.val + carry;
            result.val = sum % 10;
            carry = sum / 10;
        }
        //System.out.println(carry);
        if (carry != 0) {
            result.next  = new ListNode(carry);
        }
        return reverse(dummy.next);
    }

        private ListNode reverse(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        while (head.next != null) {
            ListNode temp = head.next;
            head.next = head.next.next;
            temp.next = dummy.next;
            dummy.next = temp;
        }
        return dummy.next;
    }
}

results matching ""

    No results matching ""