题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <cstddef> class Solution { public: // 反转链表 ListNode* inverseNodes(ListNode* head) { if (head == nullptr) { return nullptr; } auto nextNode = head->next; head->next = nullptr; while (nextNode != nullptr) { auto first = nextNode->next; nextNode->next = head; head = nextNode; nextNode = first; } return head; } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ ListNode* addInList(ListNode* head1, ListNode* head2) { // write code here head1 = inverseNodes(head1); head2 = inverseNodes(head2); // std::cout << " nodes1: "; // while (head1 != nullptr) { // std::cout << head1->val << " "; // head1 = head1->next; // } // std::cout << " nodes2: "; // while (head2 != nullptr) { // std::cout << head2->val << " "; // head2 = head2->next; // } ListNode* head = nullptr; int v1 = 0, v2 = 0, v3 = 0; while (head1 != nullptr || head2 != nullptr) { v1 = 0; v2 = 0; if (head1 != nullptr) { v1 = head1->val; head1 = head1->next; } if (head2 != nullptr) { v2 = head2->val; head2 = head2->next; } v3 = v1 + v2 + v3; std::cout << v3 << std::endl; auto node = new ListNode(v3 % 10); node->next = head; v3 = v3 / 10; head = node; } if(v3 > 0) { auto node = new ListNode(v3); node->next = head; head = node; } return head; } };
在线编程练习 文章被收录于专栏
C++在线编程练习题解