-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd 1 to a Linked List Number
59 lines (47 loc) Β· 1.2 KB
/
Add 1 to a Linked List Number
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
// User function template for C++
/*
struct Node
{
int data;
struct Node* next;
Node(int x){
data = x;
next = NULL;
}
};
*/
class Solution {
private:
Node* reverse(Node* head) {
Node* prev = nullptr;
Node* current = head;
Node* next = nullptr;
while (current != nullptr) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
public:
Node* addOne(Node* head) {
if (head == nullptr) return new Node(1);
// Step 1: Reverse the linked list
head = reverse(head);
// Step 2: Add 1 to the number
Node* current = head;
int carry = 1;
while (current != nullptr && carry > 0) {
int sum = current->data + carry;
current->data = sum % 10;
carry = sum / 10;
if (carry > 0 && current->next == nullptr) {
current->next = new Node(0);
}
current = current->next;
}
// Step 3: Reverse the list back
return reverse(head);
}
};