题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
//首先反转了两个链表,然后从头部开始相加链表的节点值,直到两个链表都为空且进位为0为止。在相加过程中创建新的节点,并将它们连接到结果链表。 typedef struct ListNode ListNode; class Solution { public: ListNode* addInList(ListNode* head1, ListNode* head2) { // 首先反转两个链表 ListNode* reversedHead1 = reverseList(head1); ListNode* reversedHead2 = reverseList(head2); ListNode* result = nullptr; int carry = 0; // 相加链表节点值,直到两个链表都为空且进位为0为止 while (reversedHead1 || reversedHead2 || carry) { int sum = (reversedHead1 ? reversedHead1->val : 0) + (reversedHead2 ? reversedHead2->val : 0) + carry; carry = sum / 10; sum %= 10; // 创建新节点并连接到结果链表 ListNode* newNode = new ListNode(sum); newNode->next = result; result = newNode; // 移动到下一个节点 if (reversedHead1) reversedHead1 = reversedHead1->next; if (reversedHead2) reversedHead2 = reversedHead2->next; } return result; } // 辅助函数:反转链表 ListNode* reverseList(ListNode* head) { ListNode* prev = nullptr; ListNode* curr = head; while (curr) { ListNode* nextNode = curr->next; curr->next = prev; prev = curr; curr = nextNode; } return prev; } };