Last active
August 29, 2015 14:00
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Java: | |
public class Solution { | |
public ListNode mergeKLists(ArrayList<ListNode> lists) { | |
if(lists.size()==0) return null; | |
PriorityQueue<ListNode> q = new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>() | |
{ public int compare(ListNode a, ListNode b){ | |
return a.val>b.val?1:(a.val==b.val?0:-1); | |
} | |
}); | |
for(ListNode list:lists){ | |
if(list!=null) q.add(list); | |
} | |
ListNode head = new ListNode(0), prev = head; | |
while(q.size()!=0){ | |
ListNode temp = q.poll(); | |
prev.next = temp; | |
if(temp.next!=null) q.add(temp.next); | |
prev = prev.next; | |
} | |
return head.next; | |
} | |
} | |
C++: | |
class CompareListNode { | |
public: | |
bool operator()(ListNode *n1, ListNode *n2) // Returns true if t1 is earlier than t2 | |
{ | |
if (n1->val >= n2->val) | |
return true; | |
else | |
return false; | |
} | |
}; | |
class Solution { | |
public: | |
ListNode *mergeKLists(vector<ListNode *> &lists) {. | |
priority_queue<ListNode *, vector<ListNode *>, CompareListNode> q; | |
for (const auto &list : lists) { | |
if (list != NULL) { | |
q.push(list); | |
} | |
} | |
ListNode *head = new ListNode(0);; | |
ListNode *curr = head; | |
while (q.size() > 0) { | |
ListNode *temp = q.top(); | |
curr->next = temp; | |
curr = curr->next; | |
q.pop(); | |
if (temp->next != NULL) { | |
q.push(temp->next); | |
} | |
} | |
curr = head->next; | |
delete head; | |
return curr; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment