题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
ListNode* RverseList(ListNode* pHead) {
ListNode* next = nullptr;
ListNode* prev = nullptr;
ListNode* curr = pHead;
// ListNode* next = nullptr;
if(pHead == nullptr) {
return nullptr;
}
while(curr != nullptr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next; // 收尾呼应
}
return prev;
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @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;
}
ListNode* rv1 = RverseList(head1);
ListNode* rv2 = RverseList(head2);
int carry = 0;
ListNode* res = new ListNode(-1);
ListNode* curr = res; // 必须用头结点拷贝才能操作next
while(rv1 != nullptr || rv2 != nullptr || carry != 0){
int val1 = rv1 != nullptr ? rv1->val : 0;
int val2 = rv2 != nullptr ? rv2->val : 0;
int temp = val2 + val1 + carry;
carry = temp / 10;
temp = temp % 10;
curr->next = new ListNode(temp);
curr = curr->next;
if(rv1 != nullptr) {
rv1 = rv1->next;
}
if(rv2 != nullptr) {
rv2 = rv2->next;
}
}
return RverseList(res->next);
}
};
查看3道真题和解析
