Skip to content

Commit 32066f0

Browse files
authored
Create 2816. Double a Number Represented as a Linked List (#473)
2 parents a61c1fa + 3bc4755 commit 32066f0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public:
3+
ListNode* doubleIt(ListNode* head) {
4+
// Initialize a stack to store the values of the linked list
5+
stack<int> values;
6+
int val = 0;
7+
8+
// Traverse the linked list and push its values onto the stack
9+
while (head != nullptr) {
10+
values.push(head->val);
11+
head = head->next;
12+
}
13+
14+
ListNode* newTail = nullptr;
15+
16+
// Iterate over the stack of values and the carryover
17+
while (!values.empty() || val != 0) {
18+
// Create a new ListNode with value 0 and the previous tail as its next node
19+
newTail = new ListNode(0, newTail);
20+
21+
// Calculate the new value for the current node
22+
// by doubling the last digit, adding carry, and getting the remainder
23+
if (!values.empty()) {
24+
val += values.top() * 2;
25+
values.pop();
26+
}
27+
newTail->val = val % 10;
28+
val /= 10;
29+
}
30+
31+
// Return the tail of the new linked list
32+
return newTail;
33+
}
34+
};

0 commit comments

Comments
 (0)