Advertisement
sweet1cris

Untitled

Sep 25th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.91 KB | None | 0 0
  1. public class MergeKSortedList {
  2.   public ListNode merge(List<ListNode> listOfLists) {
  3.     // Assumptions: listOfLists is not null, none of the lists is null.
  4.     PriorityQueue<ListNode> minHeap = new PriorityQueue<ListNode>(11, new
  5. MyComparator());
  6.     ListNode dummy = new ListNode(0);
  7.     ListNode cur = dummy;
  8.     for (ListNode node : listOfLists) {
  9.       if (node != null) {
  10.         minHeap.offer(node);
  11.       }
  12.     }
  13.     while (!minHeap.isEmpty()) {
  14.       cur.next = minHeap.poll();
  15.       if (cur.next.next != null) {
  16.         minHeap.offer(cur.next.next);
  17.       }
  18.       cur = cur.next;
  19.     }
  20.     return dummy.next;
  21.   }
  22.  
  23.   static class MyComparator implements Comparator<ListNode> {
  24.     @Override
  25.     public int compare(ListNode o1, ListNode o2) {
  26.       if (o1.value == o2.value) {
  27.         return 0;
  28.       }
  29.       return o1.value < o2.value  -1 : 1;
  30.     }
  31.   }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement