zoukankan      html  css  js  c++  java
  • [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;
        }
    }
  • 相关阅读:
    SpringBoot之使用外部的启动类
    CCF——最小差值(2017-12)
    CCF——买菜(2018-09)
    CCF——卖菜(2018-09)
    2792. Grammar Lessons
    2756. Lucky Transformation
    2776. String Task
    2794. Petya and Strings
    2810. Palindromic Times
    14. Football
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12496772.html
Copyright © 2011-2022 走看看