题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <memory>
#include <utility>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
auto Rev = [](ListNode* head) {
auto prev = head;
auto cur = prev->next;
if(not cur) return prev;
prev->next = nullptr;
while(cur) {
auto t = cur->next;
cur->next = prev;
prev = cur;
cur = t;
}
return prev;
};
auto rh1 = Rev(head1);
auto root = rh1;
auto rh2 = Rev(head2);
while(rh2) {
rh1->val += rh2->val;
rh2 = rh2->next;
if(not rh1->next) break;
rh1 = rh1->next;
}
if(rh2) {
rh1->next = rh2;
}
// 进位处理
for(auto cur = root; cur; cur = cur->next) {
auto& v = cur->val;
if(v >= 10) {
if(not cur->next) {
mem.emplace_back(std::make_unique<ListNode>(0));
cur->next = mem.back().get();
}
cur->next->val += v / 10;
v %= 10;
}
}
return Rev(root);
}
std::vector<std::unique_ptr<ListNode>> mem;
};