[LeetCode] Double a Number Represented as a Linked List

2816. Double a Number Represented as a Linked List

You are given the head of a non-empty linked list representing a non-negative integer without leading zeroes.

Return the head of the linked list after doubling it.

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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* doubleIt(ListNode* head) {
vector<ListNode*> st;
ListNode* runner = head;
while(runner) {
st.push_back(runner);
runner = runner->next;
}
ListNode* res = nullptr;
int carry = 0;
while(st.size()) {
res = st.back(); st.pop_back();
res->val = (res->val * 2 + carry);
carry = (res->val) / 10;
res->val %= 10;
}
if(carry) {
ListNode* node = new ListNode(carry, res);
res = node;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/08/13/PS/LeetCode/double-a-number-represented-as-a-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.