题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if(pHead1==nullptr) return pHead2; if(pHead2==nullptr) return pHead1; ListNode* dummy=new ListNode(-1); ListNode* cur=dummy; ListNode* cur1=pHead1; ListNode* cur2=pHead2; while(cur1!=nullptr&&cur2!=nullptr) { if(cur1->val>=cur2->val) { cur->next=cur2; cur2=cur2->next; } else { cur->next=cur1; cur1=cur1->next; } cur=cur->next; } if(cur1==nullptr) { cur->next=cur2; } if(cur2==nullptr) { cur->next=cur1; } return dummy->next; } ListNode* divideMerge(vector<ListNode*>& lists,int l,int r) { if(l>r) return nullptr; else if(l==r) return lists[l]; int m=(l+r)/2; return Merge(divideMerge(lists,l,m),divideMerge(lists,m+1,r)); } ListNode* mergeKLists(vector<ListNode*>& lists) { return divideMerge(lists,0,lists.size()-1); } };
归并排序