forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplus-one-linked-list.cpp
46 lines (40 loc) · 979 Bytes
/
plus-one-linked-list.cpp
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
43
44
45
46
// Time: O(n)
// Space: O(1)
/**
* 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) {
auto rev_head = reverseList(head);
auto curr = rev_head;
int carry = 1;
while (curr && carry) {
curr->val += carry;
carry = curr->val / 10;
curr->val %= 10;
if (carry && !curr->next) {
curr->next = new ListNode(0);
}
curr = curr->next;
}
return reverseList(rev_head);
}
private:
ListNode* reverseList(ListNode* head) {
auto dummy = ListNode{0};
auto curr = head;
while (curr) {
auto tmp = curr->next;
curr->next = dummy.next;
dummy.next = curr;
curr = tmp;
}
return dummy.next;
}
};