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