码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] 904. Plus One Linked List

时间:2020-03-15 13:27:25      阅读:48      评论:0      收藏:0      [点我收藏+]

标签:esc   head   except   write   leading   param   ini   ret   integer   

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

标签:esc   head   except   write   leading   param   ini   ret   integer   

原文地址:https://www.cnblogs.com/xuanlu/p/12496772.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!