题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <cstdlib>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
if (head1 == nullptr) {
return head2;
}
if (head2 == nullptr) {
return head1;
}
head1 = Reverse(head1);
head2 = Reverse(head2);
ListNode* pHead = new ListNode(0);
pHead->next = nullptr;
int carry = 0;
ListNode* p1, *p2;
p1 = head1;
p2 = head2;
while (p1 != nullptr || p2 != nullptr) {
int a, b;
if (p1 == nullptr) {
a = 0;
} else {
a = p1->val;
}
if (p2 == nullptr) {
b = 0;
} else {
b = p2->val;
}
int sum = (a + b + carry) % 10;
carry = (a + b + carry) / 10;
ListNode* s = new ListNode(sum);
s->next = pHead->next;
pHead->next = s;
if (p1 != nullptr) {
p1 = p1->next;
}
if (p2 != nullptr) {
p2 = p2->next;
}
}
if (carry != 0) {
ListNode* s = new ListNode(carry);
s->next = pHead->next;
pHead->next = s;
}
return pHead->next;
}
ListNode* Reverse(ListNode* head) {//翻转链表(原本的翻转方法时间复杂度过高)
if(head==nullptr || head->next==nullptr)
return head;
ListNode *a=nullptr, *b=head, *c=head->next;
while(c!=nullptr) {
b->next=a;
a=b;
b=c;
c=c->next;
}
b->next=a;
return b;
}
};
