merge k sorted lists

 1 bool cmp(ListNode * a ,ListNode * b )
 2 {
 3     return a->val >= b-> val;
 4 }
 5 class Solution {
 6 public:
 7     ListNode *mergeKLists(vector<ListNode *> &lists) {
 8         // Start typing your C/C++ solution below
 9         // DO NOT write int main() function
10         if( lists.empty() ) return NULL;
11         vector<ListNode *> v;
12         ListNode * head = new ListNode(0);
13         ListNode * p = head;
14         for(int i=0;i<lists.size();i++)
15             if( lists[i] != NULL )
16                 v.push_back( lists[i] );
17         make_heap(v.begin(),v.end(), cmp );
18         while( !v.empty() )
19         {
20             p -> next = v[0];
21             p = p-> next;
22             pop_heap( v.begin(), v.end(), cmp );
23             v.pop_back();
24             if( p -> next != NULL )
25             {
26                 v.push_back( p->next );
27                 push_heap(v.begin(),v.end() ,cmp);
28             }
29                 
30         }
31         return head -> next;
32         
33     }
34 };

 

posted on 2013-09-04 10:24  jumping_grass  阅读(205)  评论(0)    收藏  举报

导航