Saturday, September 20, 2014

LeetCode: Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

 /**  
  * Definition for singly-linked list.  
  * struct ListNode {  
  *   int val;  
  *   ListNode *next;  
  *   ListNode(int x) : val(x), next(NULL) {}  
  * };  
  */  
   
   #define tr(c,it) for(decltype((c).begin()) (it) = (c).begin(); (it) != (c).end(); (it)++)  
    
   typedef ListNode ln;   
   
   struct compare{  
     bool operator() (ListNode *a, ListNode *b) const  
     {  
       return (a->val > b->val);  
     }  
   };  
   
   ListNode *mergeKLists(vector<ListNode *> &lists) {  
     int n = lists.size();  
     if(n<1)return NULL;  
     vector<ListNode *> Cur;  
     ListNode *head = NULL, *last = NULL;  
     priority_queue<ListNode *,vector<ListNode *>, compare > pq;  
     tr(lists,it)  
     {  
       int i = it - lists.begin();  
       Cur.push_back(*it);  
       if(*it)  
         pq.push(*it);  
     }  
     while(!pq.empty())  
     {  
       ln *min = pq.top();  
       pq.pop();  
       if(!head)  
       {  
         head = min;  
         last = min;  
       }  
       else  
       {  
         last->next = min;  
         last = min;  
       }  
       if(last->next)  
         pq.push(last->next);  
     }  
     return head;  
   }  

No comments:

Post a Comment