题解 | #链表相加(二)#
链表相加(二)
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) {
if (head == nullptr || head->next == nullptr)
return 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);
// 设置进位carry,开始模拟相加
int carry = 0;
ListNode *newHead = new ListNode(-1);
ListNode *cur = newHead;
while (head1 != nullptr || head2 != nullptr || carry != 0) {
int val1 = head1 == nullptr ? 0 : head1->val;
int val2 = head2 == nullptr ? 0 : head2->val;
int temp = val1 + val2 + carry;
carry = temp / 10; // 进位
temp %= 10;
cur->next = new ListNode(temp);
cur = cur->next;
if (head1 != nullptr)
head1 = head1->next;
if (head2 != nullptr)
head2 = head2->next;
}
// 反转结果链表
return ReverseList(newHead->next);
}
};
联想公司福利 1518人发布
查看12道真题和解析