lamiastella

mergeKList

May 1st, 2016
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. /**
  2. * Definition for singly-linked list.
  3. * class ListNode {
  4. * public int val;
  5. * public ListNode next;
  6. * ListNode(int x) { val = x; next = null; }
  7. * }
  8. */
  9. public class Solution {
  10.  
  11. public ListNode mergeKLists(ArrayList<ListNode> A) {
  12.  
  13. TreeMap<Integer, ArrayList<ListNode>> map = new TreeMap<>();
  14. ListNode node;
  15. ArrayList<ListNode> list;
  16. int val;
  17.  
  18. for (ListNode head : A) {
  19. node = head;
  20. while (node != null) {
  21. val = node.val;
  22.  
  23. if (map.containsKey(val)) {
  24. list = map.get(val);
  25. list.add(node);
  26. } else {
  27. list = new ArrayList<>();
  28. list.add(node);
  29. map.put(val, list);
  30. }
  31.  
  32. node = node.next;
  33. }
  34. }
  35.  
  36. ListNode head = null;
  37. node = null;
  38.  
  39. for (Map.Entry<Integer, ArrayList<ListNode>> entry : map.entrySet()) {
  40.  
  41. list = entry.getValue();
  42.  
  43. for (ListNode n : list) {
  44. if (head == null)
  45. head = n;
  46. if (node != null)
  47. node.next = n;
  48. node = n;
  49. }
  50.  
  51.  
  52. }
  53.  
  54. return head;
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment