题解 | 合并两个排序的链表
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=383&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <set>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
multiset<int> s;
ListNode* p1 = pHead1;
ListNode* p2 = pHead2;
while (p1) {
s.insert(p1->val);
p1=p1->next;
}
while (p2) {
s.insert(p2->val);
p2=p2->next;
}
ListNode* dummy = new ListNode(-1);
ListNode* p = dummy;
for(int c : s){
p->next = new ListNode(c);
p = p->next;
}
return dummy->next;
}
};
直接把表中的数塞多重集合里,然后用头插法搞个新表即可