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 }