思路:
常规思路
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(checkListsNull(lists)) return null;
if(lists.length ==0 ) return null;
if(lists.length ==1) return lists[0];
ListNode headNode = new ListNode();
ListNode firstNode = new ListNode();
ListNode currentSmallestNode = new ListNode();
ListNode currentSmallestNextNode = new ListNode();
currentSmallestNode = getsmallestNode(lists);
firstNode = currentSmallestNode;
headNode.next = firstNode;
lists = generateNewsListNodes(lists,currentSmallestNode);
while(lists.length > 0){
currentSmallestNextNode = getsmallestNode(lists);
currentSmallestNode.next = currentSmallestNextNode;
currentSmallestNode = currentSmallestNextNode;
lists = generateNewsListNodes(lists,currentSmallestNode);
}
return headNode.next;
}
public boolean checkListsNull(ListNode[] lists){
boolean checkListsNull = true;
for(ListNode node : lists){
checkListsNull &= (node == null);
}
return checkListsNull;
}
public ListNode[] generateNewsListNodes(ListNode[] lists,
ListNode currentSmallestNode){
List<ListNode> newLists = new ArrayList<>();
for(int i=0; i<lists.length ; i++){
if(lists[i] !=null) {
if(lists[i].val == currentSmallestNode.val) {
lists[i] = lists[i].next;
break;
}
}
}
for(int i=0; i<lists.length ; i++){
if(lists[i] !=null) {
newLists.add(lists[i]);
}
}
return newLists.toArray(new ListNode[newLists.size()]);
}
public ListNode getsmallestNode(ListNode[] lists){
ListNode smallestNode = new ListNode(Integer.MAX_VALUE);
for(ListNode node : lists){
if(node != null && node.val < smallestNode.val ) smallestNode = node;
}
return smallestNode;
}
}