-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
plus-one-linked-list.cpp
88 lines (76 loc) · 1.78 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Time: O(n)
// Space: O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// Two pointers solution.
class Solution {
public:
ListNode* plusOne(ListNode* head) {
if (!head) {
return nullptr;
}
auto dummy = new ListNode{0};
dummy->next = head;
auto left = dummy, right = head;
while (right->next) {
if (right->val != 9) {
left = right;
}
right = right->next;
}
if (right->val != 9) {
++right->val;
} else {
++left->val;
right = left->next;
while (right) {
right->val = 0;
right = right->next;
}
}
if (dummy->val == 0) {
head = dummy->next;
delete dummy;
return head;
}
return dummy;
}
};
// Time: O(n)
// Space: O(1)
class Solution2 {
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) {
ListNode dummy{0};
auto curr = head;
while (curr) {
auto tmp = curr->next;
curr->next = dummy.next;
dummy.next = curr;
curr = tmp;
}
return dummy.next;
}
};