package com.example.demo.leecode;
/**
* 合并K个升序链表
* @Date 2020/12/15
* @author Tang
*
* 给你一个链表数组,每个链表都已经按升序排列。
* 请你将所有链表合并到一个升序链表中,返回合并后的链表。
*/
public class MergeKSortedLists {
public ListNode execute(ListNode[] lists){
if(lists.length == 0){
return null;
}
ListNode firstNode = lists[0];
for(int i = 1; i < lists.length; i++){
firstNode = mergeTwoList(firstNode, lists[i]);
}
return firstNode;
}
private ListNode mergeTwoList(ListNode l1, ListNode l2){
ListNode first;
ListNode end;
if(l1.val <= l2.val){
first = l1;
l1 = l1.next;
}else{
first = l2;
l2 = l2.next;
}
end = first;
//循环排序成一条链表 直到其中一条到头了
while(l1 != null && l2 != null){
if(l1.val <= l2.val){
end.next = l1;
end = l1;
l1 = l1.next;
}else{
end.next = l2;
end = l2;
l2 = l2.next;
}
}
while(l1 != null){
end.next = l1;
end = l1;
l1 = l1.next;
}
while(l2 != null){
end.next = l2;
end = l2;
l2 = l2.next;
}
return first;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(3);
ListNode l4 = new ListNode(5);
ListNode l5 = new ListNode(2);
ListNode l6 = new ListNode(4);
ListNode l7 = new ListNode(8);
ListNode l8 = new ListNode(9);
ListNode l9 = new ListNode(2);
ListNode l10 = new ListNode(3);
ListNode l11 = new ListNode(4);
ListNode l12 = new ListNode(5);
l1.next = l2; l2.next = l3; l3.next = l4;
l5.next = l6; l6.next = l7; l7.next = l8;
l9.next = l10; l10.next = l11; l11.next = l12;
ListNode[] list = {l1, l5, l9};
ListNode execute = new MergeKSortedLists().execute(list);
System.out.println(execute.val);
while(execute.hasNext()){
execute = execute.next;
System.out.println(execute.val);
}
}
}
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
boolean hasNext(){
return next != null;
}
}