Fork me on GitHub

Plus One Linked List

Description

https://leetcode.com/problems/plus-one-linked-list/

Solution

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* 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) {
if (head == NULL) return head;

ListNode* cur = new ListNode(0);
ListNode* ret = cur;
cur->next = head;

while(cur->next) {
stack<ListNode*> st;
st.push(cur); //The digit before the leading 9
while(cur->next && cur->next->val == 9) {
cur = cur->next;
st.push(cur);
}
if(cur->next == NULL) {
//The last digit is 9
while(st.size() > 1) {
ListNode* item = st.top();
st.pop();
item->val = 0;
}
st.top()->val += 1;
return ret->val ? ret : ret->next;
}
//Find the next 9
while(cur->next && cur->next->val != 9) cur = cur->next;
}
//The last digit is not 9
cur->val += 1;
return ret->next;
}
};