题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* ReverseList(ListNode* head) {
ListNode* cur = head;
ListNode* pre = nullptr;
while (cur != nullptr) {
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
if (head1 == nullptr) return head2;
if (head2 == nullptr) return head1;
head1 = ReverseList(head1);
head2 = ReverseList(head2);
int carry = 0;
ListNode* res = new ListNode(0);
ListNode* ans = res;
while (head1 != nullptr || head2 != nullptr) {
ListNode* temp = new ListNode(0);
ans->next = temp;
ans = temp;
if (head1 != nullptr && head2 != nullptr) {
temp->val = head1->val + head2->val + carry;
if (temp->val >= 10) {
carry = 1;
temp->val = (temp->val) % 10;
}else{
carry =0;
}
head1 = head1->next;
head2 = head2->next;
}
else if (head1 == nullptr && head2 != nullptr) {
temp->val = head2->val + carry;
if (temp->val >= 10) {
carry = 1;
temp->val = (temp->val) % 10;
}else{
carry =0;
}
head2 = head2->next;
}
else if (head1 != nullptr && head2 == nullptr) {
temp->val = head1->val + carry;
if (temp->val >= 10) {
carry = 1;
temp->val = (temp->val) % 10;
}else{
carry =0;
}
head1 = head1->next;
}
}
if (carry != 0) {
ListNode* temp = new ListNode(carry);
ListNode* ans = res;
while (ans->next != nullptr) {
ans = ans->next;
}
ans->next = temp;
}
return ReverseList(res->next);
}
};


查看22道真题和解析