Problem Description:
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.

1
2
3
4
5
6
Example:
Input:
1->2->3

Output:
1->2->4

Solution:
The key point is to find 9’s.
For example: 8->7->9->9
Add dummy: 0->8->7->9->9
The lastNotNine is 7.
7 + 1 = 8
9 change to 0.
We got 0->8->8->0->0
return dummy.next

For example: 9->9->9
Add dummy: 0->9->9->9
The lastNotNine is 0.
0 + 1 = 1
9 change to 0.
We got 1->0->0->0
return dummy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* plusOne(ListNode* head) {

ListNode* dmy = new ListNode(0);
ListNode* lastNot9 = dmy;
dmy->next = head;
for (ListNode* n = head; n != NULL; n = n->next) {
if (n->val != 9) lastNot9 = n; /* invariant: [lastNot9.next, tail] are all 9*/
}

lastNot9->val++;
for (ListNode* n = lastNot9->next; n != NULL; n = n->next) {
n->val = 0;
}
return dmy->val == 1 ? dmy : head;
}
};