思路:将每个链表的头存在最小堆中,每次取堆首,然后将取出节点的下一个放入堆中中。
1 class cmp{ 2 public: 3 bool operator()(ListNode* l1,ListNode* l2) 4 { 5 return l1->val>l2->val; 6 } 7 }; 8 class Solution { 9 public: 10 ListNode* mergeKLists(vector<ListNode*>& lists) { 11 ListNode* head,*ptr1,*ptr2; 12 priority_queue<ListNode*,vector<ListNode*>,cmp> minHeap; 13 for(int i=0;i<lists.size();i++) 14 if(lists[i]!=NULL) 15 minHeap.push(lists[i]); 16 if(minHeap.empty()) 17 return NULL; 18 head = ptr1 = ptr2= minHeap.top(); 19 minHeap.pop(); 20 if(ptr1->next!=NULL) 21 minHeap.push(ptr1->next); 22 23 while(!minHeap.empty()) 24 { 25 ptr1 = minHeap.top(); 26 // cout<<ptr1->val<<endl; 27 ptr2->next = ptr1; 28 ptr2 = ptr2->next; 29 minHeap.pop(); 30 if(ptr1->next==NULL) 31 continue; 32 minHeap.push(ptr1->next); 33 } 34 return head; 35 } 36 };
原文:http://www.cnblogs.com/ZhangYushuang/p/4478292.html