题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <cstddef> #include <iostream> #include <set> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { // write code here multiset<int> s1; multiset<int> s2; if (pHead1 == NULL&& pHead1 ==NULL) return nullptr; while (pHead1) { s1.insert(pHead1->val); pHead1 = pHead1->next; } while (pHead2) { s2.insert(pHead2->val); pHead2 = pHead2->next; } s1.insert(s2.begin(), s2.end()); // 创建新链表的头节点 ListNode* dummy = new ListNode(0); // 使用哑节点简化操作 ListNode* now = dummy; // 用于构建新链表的指针 // 遍历set,创建链表节点 for (set<int>::iterator it = s1.begin(); it != s1.end(); ++it) { now->next = new ListNode(*it); now = now->next; } // 返回新链表的头,即dummy的下一个节点 ListNode* mergedHead = dummy->next; delete dummy; // 删除哑节点 return mergedHead; } };
使用multiset容器自动实现排序