Skip to content

Create 2816. Double a Number Represented as a Linked List #473

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions 2816. Double a Number Represented as a Linked List
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution {
public:
ListNode* doubleIt(ListNode* head) {
// Initialize a stack to store the values of the linked list
stack<int> values;
int val = 0;

// Traverse the linked list and push its values onto the stack
while (head != nullptr) {
values.push(head->val);
head = head->next;
}

ListNode* newTail = nullptr;

// Iterate over the stack of values and the carryover
while (!values.empty() || val != 0) {
// Create a new ListNode with value 0 and the previous tail as its next node
newTail = new ListNode(0, newTail);

// Calculate the new value for the current node
// by doubling the last digit, adding carry, and getting the remainder
if (!values.empty()) {
val += values.top() * 2;
values.pop();
}
newTail->val = val % 10;
val /= 10;
}

// Return the tail of the new linked list
return newTail;
}
};
Loading