首页 > 其他 > 详细

Plus One Linked List

时间:2017-02-17 16:45:49      阅读:175      评论:0      收藏:0      [点我收藏+]

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:

Input:
1->2->3

Output:
1->2->4


 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode plusOne(ListNode head) {
11         List<Integer> temp = new ArrayList<Integer>();
12         
13         ListNode move = head;
14         while(move != null) {
15             temp.add(move.val);
16             move = move.next;
17         }
18         
19         int carry = 1;
20         ListNode last = new ListNode(-1);
21         for(int i = temp.size() - 1; i >= 0; i--) {
22             int total = carry + temp.get(i);
23             last.val = total % 10;
24             carry = total / 10;
25             
26             ListNode pre = new ListNode(-1);
27             pre.next = last;
28             last = pre;
29         }
30         
31         if (carry == 1) {
32             last.val = 1;
33             return last;
34         } else {
35             return last.next;
36         }
37     }
38 }

 

Plus One Linked List

原文:http://www.cnblogs.com/amazingzoe/p/6410454.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!