Problem
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
Solution
class Solution {
public ListNode plusOne(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode l1 = dummy, l2 = dummy;
//12399456999
//use l1, l2 to locate 6999
while (l2.next != null) {
l2 = l2.next;
if (l2.val != 9) {
l1 = l2; //l1 stays at node 6, and l2 gets to the last node
}
}
if (l2.val == 9) {
l1.val++;
while (l1.next != null) {
l1.next.val = 0;
l1 = l1.next;
}
} else {
l2.val++;
}
if (dummy.val != 0) return dummy;
return dummy.next;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。