Question
Solution
题目大意:合并链表数组(每个链表中的元素是有序的),要求合并后的链表也是有序的
思路:遍历链表数组,每次取最小节点
Java实现:
public ListNode mergeKLists(ListNode[] lists) {
ListNode preHead = new ListNode(0);
ListNode minNode = getMinNode(lists);
ListNode tmpNode = preHead;
while (minNode != null) {
tmpNode.next = minNode;
tmpNode = minNode;
minNode = getMinNode(lists);
}
return preHead.next;
}
ListNode getMinNode(ListNode[] lists) {
int minIdx = -1;
int minVal = 0;
for (int i=0; i<lists.length; i++) {
ListNode cur = lists[i];
if (cur != null) {
if (minIdx == -1 || cur.val < minVal) {
minIdx = i;
minVal = cur.val;
}
}
}
if (minIdx != -1) {
ListNode tmpNode = lists[minIdx];
lists[minIdx] = tmpNode.next;
return tmpNode;
}
return null;
}