严氏北美IT公司面试真题汇总和解答论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Merge K Sorted Linkedlists

Go down

Merge K Sorted Linkedlists Empty Merge K Sorted Linkedlists

Post by Admin Sat Oct 21, 2017 4:52 pm

public ListNode mergeKLists(ArrayList<ListNode> lists){
if (lists == null || lists.size() == 0) {
return null;
}

PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(lists.size(), new Comparator<ListNode>(){
public int compare(ListNode a, ListNode b) {
return a.val - b.val;
}
});
for (int i = 0; i < lists.size(); i++) {
if (lists.get(i) != null) {
heap.add(lists.get(i));
}
}

ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (!heap.isEmpty()) {
ListNode head = heap.poll();
tail.next = head;
tail = head;
if (head.next != null) {
heap.add(head.next);
}
}
return dummy.next;
}


public void print(ListNode node)
{
while (node != null)
{
System.out.print(node.val + "->");
node = node.next;
}
}


public static void main(String[] args)
{
ListNode l1 = new ListNode(3);
ListNode l2 = new ListNode(7);
ListNode l3 = new ListNode(9);
l1.next = l2;
l2.next = l3;
ListNode l4 = new ListNode(2);
ListNode l5 = new ListNode(4);
ListNode l6 = new ListNode(6);
l4.next = l5;
l5.next = l6;
ListNode l7 = new ListNode(1);
ListNode l8 = new ListNode(2);
ListNode l9 = new ListNode(5);
l7.next = l8;
l8.next = l9;
MergeKSortedLinkedlists slt = new MergeKSortedLinkedlists();
slt.print(l1);
System.out.println("");
slt.print(l4);
System.out.println("");
slt.print(l7);
ArrayList<ListNode> lists=new ArrayList<ListNode>(100);
lists.add(l1);
lists.add(l4);
lists.add(l7);
System.out.println("after");
ListNode result = slt.mergeKLists(lists);
slt.print(result);
}

Admin
Admin

Posts : 124
Join date : 2017-10-21

https://csinterviewquestions.forumotion.com

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum