题解 | 链表相加(二)
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
ListNode* reNode(ListNode* node) {
ListNode* pre = nullptr;
ListNode* cur = node;
while (cur) {
ListNode* nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
head1 = reNode(head1);
head2 = reNode(head2);
int add = 0;
ListNode* dummyNode = new ListNode(0);
ListNode* node = dummyNode;
ListNode* node1 = head1;
ListNode* node2 = head2;
while (node1&&node2) {
int sum = add + node1->val + node2->val;
add = sum/10;
sum = sum%10;
node->next = new ListNode(sum);
node = node->next;
node1 = node1->next;
node2 = node2->next;
}
ListNode* lef_node = node1?node1:node2;
while(lef_node) {
int sum = add + lef_node->val;
add = sum/10;
sum %=10;
node->next = new ListNode(sum);
node = node->next;
lef_node = lef_node->next;
}
if (add) {
node->next = new ListNode(add);
}
ListNode* to_res = dummyNode->next;
to_res = reNode(to_res);
return to_res;
}
};

查看16道真题和解析