Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
学习并练习 priority_queue.
priority_queue的几个重要函数 push pop top.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ struct cmp { bool operator()(ListNode * a,ListNode *b) { return a->val > b->val; } }; class Solution { public: ListNode *mergeKLists(vector<ListNode *> &lists) { priority_queue <ListNode* , vector<ListNode*> ,cmp> qu; if(lists.size()==0)return NULL; for(int i = 0 ; i < lists.size() ; i++)if(lists[i] != NULL)qu.push(lists[i]); ListNode * head = new ListNode(0), *temp = head; head ->next = NULL; while(!qu.empty()) { temp -> next = qu.top(); qu.pop(); temp = temp->next; ListNode * tmp = temp->next; if(tmp != NULL)qu.push(tmp); } return head->next; } };