Topic:
Merge k Sorted Lists
Merge
k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Analysis:
With Multiset as a small Gan, the multiset begin is the smallest node of value.
Attention:
1, because I have defined the multiset of the ordering method (that is, the value of the node to sort), so that two different node pointers, if their value is equal, it will be judged as "the same node." and set is not allowed to duplicate values, so the following code can not use set, and with multiset!
2, the code I was used multiset, in fact, should be used with small Gan, but there is no ready-made Gan in C + + available, then lazy.
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; */struct Mysort {bool operator () (const listnode*const &A,CONST listnode*const &b) const {return a-& gt;val<b->val; } }; Class Solution {public:listnode* mergeklists (vector<listnode*>& lists) {int size=lists.size (); multiset<listnode*,mysort> table; for (int i=0;i<size;++i) {if (lists[i]!=nullptr) Table.emplace (Lists[i]); } ListNode Helper (0),*cur=&helper; while (!table.empty ()) {listnode* tmp=*table.begin (); int smallest=tmp->val; Cur->next=new ListNode (smallest); cur=cur->next; if (tmp->next==nullptr) {table.erase (Table.begin ()); } else { Table.erase (Table.begin ()); Table.emplace (Tmp->next); }} return helper.next; }};
Leetcode-merge k Sorted Lists