1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 Ten structHelper { OneListNode *head; A intLen; -Helper (ListNode *h,intl): Head (h), Len (l) {} - }; the - classhelpercmp { - Public: - BOOL operator() (ConstHelper &a,ConstHelper &b) { + returnA.len >B.len; - } + }; A at classSolution { - Public: -Priority_queueHeap; - -InlineintListsize (ListNode *head) { - intLen =0; in for(; head! = nullptr; head = Head->next, len++ ); - returnLen; to } +ListNode *mergeklists (Vector<listnode *> &lists) { - if(Lists.empty ())returnnullptr; the if(lists.size () = =1)returnlists[0]; *ListNode *head = nullptr, *left = nullptr, *right =nullptr; $ for(Auto list:lists) {Panax Notoginseng Heap.push (Helper (list, listsize (list )); - } the while(Heap.size ()! =1 ) { +left =Heap.top (). Head; A Heap.pop (); theright =Heap.top (). Head; + Heap.pop (); -Head =Mergelist (left, right); $ Heap.push (Helper (head, Listsize (head))); $ } - returnHeap.top (). Head; - } theListNode *mergelist (ListNode *a, ListNode *b) { -ListNode Dummy (0);WuyiListNode *tail = &dummy; the while(A! = nullptr && B! =nullptr) { - if(A-> Val <= b->val) { WuTail->next =A; -A = a->Next; About}Else { $Tail->next =b; -b = b->Next; - } -Tail = tail->Next; A } +Tail->next = A = = nullptr?b:a; the returnDummy.next; - } $};
Leetcodeoj:merge k Sorted Lists merge sort + Minimum heap