[LintCode] 904. Plus One Linked List

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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;
    }
}

 

以上是关于[LintCode] 904. Plus One Linked List的主要内容,如果未能解决你的问题,请参考以下文章

407 加一

Plus One

[Leetcode] Plus One

(分类讨论, 情景模拟) lintcode 640. One Edit Distance, leetcode 388,intcode 645. 13. 12. 659. 660

66_Plus-One

66. Plus One