题解 | #链表相加(二)#
链表相加(二)
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* addInList(ListNode* head1, ListNode* head2) {
// write code here
if (!head1) {
return head2;
}
if (!head2) {
return head1;
}
ListNode* new_head1 = reverseList(head1);
ListNode* new_head2 = reverseList(head2);
ListNode* res_head = new_head1;
ListNode* pre_new_head1 = nullptr;
int jinwei = 0;
while (new_head1 && new_head2) {
int sum = new_head1->val + new_head2->val + jinwei;
jinwei = sum / 10;
int yushu = sum % 10;
new_head1->val = yushu;
pre_new_head1 = new_head1;
new_head1 = new_head1->next;
new_head2 = new_head2->next;
}
if (new_head1) {
while (new_head1) {
int sum = new_head1->val + jinwei;
jinwei = sum / 10;
int yushu = sum % 10;
new_head1->val = yushu;
pre_new_head1 = new_head1;
new_head1 = new_head1->next;
}
if (jinwei > 0) {
pre_new_head1->next = new ListNode(jinwei);
}
}
if (new_head2) {
while (new_head2) {
int sum = new_head2->val + jinwei;
jinwei = sum / 10;
int yushu = sum % 10;
pre_new_head1->next = new ListNode(yushu);
pre_new_head1 = pre_new_head1->next;
new_head2 = new_head2->next;
}
if (jinwei > 0) {
pre_new_head1->next = new ListNode(jinwei);
}
}
return reverseList(res_head);
}
private:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
while (cur) {
ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
};
查看14道真题和解析