[LintCode] 904. Plus One Linked List

Given a non-negative integer represented as non-empty a 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

Example1

Input: 1 -> 2 -> 3 -> null
Output: 1 -> 2 -> 4 -> null
Explanation:
123 + 1 = 124


/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: the first Node
     * @return: the answer after plus one
     */
    public ListNode plusOne(ListNode head) {
        // Write your code here
        ListNode newHead = reverse(head);
        ListNode cur = newHead;
        
        int carry = 1;
        while (cur != null) {
            int tmp = cur.val + carry;
            carry = tmp / 10;
            cur.val = tmp % 10;
            cur = cur.next;
        }
        if (carry != 0) {
            head.next = new ListNode(1);
        }
        return reverse(newHead);
    }
    
    private ListNode reverse(ListNode head) {
        ListNode prev = null, nxt = null;
        while (head != null) {
            nxt = head.next;
            head.next = prev;
            prev = head;
            head = nxt;
        }
        return prev;
    }
}
原文地址:https://www.cnblogs.com/xuanlu/p/12496772.html