runnig

Merge K Sorted Lists

Feb 5th, 2013
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. /*
  2.  
  3. http://leetcode.com/onlinejudge#question_115
  4.  
  5. Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
  6. */
  7. typedef std::pair<int, ListNode*> heapvalue_t;
  8.  
  9. bool operator < ( const heapvalue_t & a, const heapvalue_t & b)
  10. {
  11.     return a.first > b.first; // for minheap
  12. }
  13.  
  14. class Solution {
  15. public:
  16.  
  17.     ListNode * mergeKLists(vector<ListNode *> &lists)
  18.     {    
  19.         if(lists.empty()) { return NULL; }
  20.                
  21.         std::priority_queue<heapvalue_t> minheap;
  22.         const int N = lists.size();
  23.        
  24.         for(int i = 0; i < N; ++i)
  25.         {
  26.             ListNode * node = lists[i];            
  27.             if(node) { minheap.push(make_pair(node->val, node)); }
  28.         }
  29.        
  30.         minheap.push(make_pair(INT_MAX, (ListNode*)NULL)); // satellite - end of stream
  31.         ListNode * head = NULL, * tail;
  32.                
  33.         while(!minheap.empty())
  34.         {            
  35.             ListNode * node = minheap.top().second;            
  36.             minheap.pop();
  37.            
  38.             if(!head) { head = tail = node; }
  39.             else if(tail) { tail->next = node; tail = node; }
  40.            
  41.             if(node && node->next)
  42.             {            
  43.                 minheap.push(make_pair(node->next->val, node->next));
  44.             }
  45.         }
  46.         return head;
  47.     }
  48. };
Advertisement
Add Comment
Please, Sign In to add comment