# LeetCode题解——23.合并K个排序链表

输入:
[
1->4->5,
1->3->4,
2->6
]



# Java

PS：注意空链表的处理，采用跳过，何时进行递归？找到最小的头结点，就需要递归，采用标志位flag实现。

package shen.leetcode.solution;

public class Solution_23 {
private static class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}
}

public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(4);
ListNode node3 = new ListNode(5);
node1.next = node2;
node2.next = node3;
ListNode node4 = new ListNode(1);
ListNode node5 = new ListNode(3);
ListNode node6 = new ListNode(4);
node4.next = node5;
node5.next = node6;
ListNode node7 = new ListNode(2);
ListNode node8 = new ListNode(6);
node7.next = node8;
ListNode n = mergeKLists(new ListNode[]{node1,node4,node7});
}

public static ListNode mergeKLists(ListNode[] lists) {
// 先找最小的头
int min = Integer.MAX_VALUE;
int index = 0;
boolean flag = false;
for (int i = 0; i < lists.length; i++) {
// 跳过空链表
if (lists[i] != null && lists[i].val <= min) {
index = i;
min = lists[i].val;
flag = true;
}
}
if (flag) {
// 拿到小头
ListNode newRoot = lists[index];
// 去掉原链表的小头
lists[index] = newRoot.next;
newRoot.next = mergeKLists(lists);
return newRoot;
}
return null;

}
}