Advertisement
Guest User

Untitled

a guest
Jun 19th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode mergeKLists(ListNode[] lists) {
  11. Comparator<ListNode> com = new Comparator<ListNode>() {
  12. public int compare(ListNode l1, ListNode l2) {
  13. return l1.val - l2.val;
  14. }
  15. };
  16.  
  17. PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(1, com);
  18. ListNode dummy = new ListNode(0);
  19. ListNode cur = dummy;
  20. for (ListNode li: lists) {
  21. if (li == null) {
  22. continue;
  23. }
  24. pq.offer(li);
  25. }
  26.  
  27. while (!pq.isEmpty()) {
  28. ListNode min = pq.poll();
  29. cur.next = min;
  30. cur = cur.next;
  31. if (min.next != null) {
  32. pq.offer(min.next);
  33. }
  34. }
  35. cur.next = null;
  36. return dummy.next;
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement