Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* 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) {
ArrayList<ListNode> listSortedbyNode = new ArrayList<ListNode>();
for(ListNode node : lists){
if(node == null){
continue;
}
//insert sort
int i = 0;
for(; i < listSortedbyNode.size(); i++){
if(node.val < listSortedbyNode.get(i).val){
break;
}
}
listSortedbyNode.add(i, node);
}
ArrayList<ListNode> mergedList = new ArrayList<ListNode>();
while(listSortedbyNode.size()!=0){
ListNode startNode = listSortedbyNode.get(0);
ListNode nextSmallNode = null;
if(listSortedbyNode.size()>=2){
nextSmallNode = listSortedbyNode.get(1);
}
while(startNode!=null && (nextSmallNode == null ||startNode.val <= nextSmallNode.val )){
mergedList.add(startNode);
startNode = startNode.next;
}
if(startNode == null || nextSmallNode == null){
listSortedbyNode.remove(0);
}else if ( startNode.val > nextSmallNode.val ){
//insert startNode to the proper position
listSortedbyNode.remove(0);
int i = 0;
for(; i < listSortedbyNode.size(); i++){
if(startNode.val < listSortedbyNode.get(i).val){
break;
}
}
listSortedbyNode.add(i, startNode);
}
}
ListNode node = null;
if(mergedList.size()>0){
node = mergedList.get(0);
for(int i = 1; i<mergedList.size();i++){
mergedList.get(i-1).next = mergedList.get(i);
}
mergedList.get(mergedList.size()-1).next = null;
}
return node;
}
}