Topic Links:
https://leetcode.com/problems/merge-k-sorted-lists/
Topic Analysis:
Method 1:
By dividing the method, the K-linked list is divided into two parts, respectively, to merge the two parts, until the last only two, you can use the merge function to merge two linked lists
Time complexity Analysis: (to be written)
The code is as follows:
classSolution { Public: ListNode* Mergeklists (vector<listnode*>&lists) { if(Lists.empty ()) {returnNULL; } returnMergelist (lists,0, Lists.size ()-1); }Private: ListNode* Mergelist (vector<listnode*> &lists,intLintr) {if(L <r) {intm = (L + r)/2; ListNode*L1 =mergelist (lists, L, M); ListNode*L2 = mergelist (lists, m+1, R); returnmergelist (L1, L2); } Else { returnLists[l]; }} ListNode*mergelist (ListNode *l1, ListNode *L2) {ListNode Dummy (-1); ListNode*P1 =L1; ListNode*P2 =L2; ListNode*p = &dummy; while(P1! = NULL && P2! =NULL) { if(P1->val < p2->val) {P->next =P1; P1= p1->Next; } Else{p->next =P2; P2= p2->Next; } P= p->Next; } if(P1! =NULL) {P->next =P1; } if(P2! =NULL) {P->next =P2; } returnDummy.next; }};
Method 2:
Using heaps to implement (in writing)
Leetcode-merge k Sorted Lists