leetcode--Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
method 1: use PriorityQueue (simple)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeKLists(List<ListNode> lists) {
ListNode newHead = new ListNode(0);
ListNode currentNode = newHead;
if(lists.size() > 0){
PriorityQueue<ListNode> nodes = new PriorityQueue<ListNode>(lists.size(), new Comparator<ListNode>(){
public int compare(ListNode l, ListNode n){
return Integer.compare(l.val, n.val);
}
});
for(int i = 0; i < lists.size(); ++i)
if(lists.get(i) != null)
nodes.add(lists.get(i));
while(!nodes.isEmpty()){
ListNode nodeToSort = nodes.poll();
if(nodeToSort.next != null)
nodes.add(nodeToSort.next);
currentNode.next = nodeToSort;
currentNode = currentNode.next;
}
}
return newHead.next;
}
}
method 2: merge 2 lists each step.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
ListNode head = null;
if(!lists.isEmpty()){
while(lists.size() > 1){
ListNode first = lists.remove(0);
ListNode second = lists.remove(0);
ListNode newNode = merge2Lists(first, second);
lists.add(0, newNode);
}
head = lists.get(0);
}
return head;
}
public ListNode merge2Lists(ListNode first, ListNode second){
ListNode head = new ListNode(0);
ListNode nextNode = head;
while(first != null && second != null){
if(first.val <= second.val){
nextNode.next = first;
first = first.next;
nextNode = nextNode.next;
}
else{
nextNode.next = second;
second = second.next;
nextNode = nextNode.next;
}
}
if(first == null)
nextNode.next = second;
else
nextNode.next = first;
head = head.next;
return head;
}
}

浙公网安备 33010602011771号