题解 | 链表相加(二)_c++
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
#include<iostream>
using namespace std;
#include<bits/stdc++.h>
class Solution {
public:
ListNode* addInList(ListNode* head1, ListNode* head2) {
if (!head1 || !head2) return !head1 ? head2 : head1;
function<ListNode*(ListNode*)> reverse = [&](ListNode * node)->ListNode* {
ListNode* pre = nullptr, * last = node;
while (last) {
ListNode* tmp = last->next;
last->next = pre;
pre = last;
last = tmp;
}
return pre;
};
ListNode* l1 = reverse(head1), * l2 = reverse(head2);
ListNode* root = new ListNode(0),* cur = root;
int jinwei = 0;
while (l1 || l2 || jinwei) {
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + jinwei;
jinwei = sum / 10;
cur->next = new ListNode(sum % 10);
cur = cur->next;
if(l1) l1 = l1->next;
if(l2) l2 = l2->next;
}
return reverse(root->next);
}
};
