//合并两个有序链表 方法一循环
public static Chain mergeMutiChainOfTwo(Chain c1,Chain c2) {
if (c1==null||c2==null) {
return c2==null?c1:c2;
}
Chain res=new Chain(0);
Chain tmp=res;
while (c1!=null&&c2!=null) {
if (c1.value<c2.value) {
tmp.next=c1;
c1=c1.next;
}else {
tmp.next=c2;
c2=c2.next;
}
tmp=tmp.next;
}
if (c1!=null) {
tmp.next=c1;
}
else {
tmp.next=c2;
}
return res.next;
}
//合并两个有序链表 方法二 递归
public static Chain mergeMutiChainOfTwo2(Chain c1,Chain c2) {
if (c1==null||c2==null) {
return c2==null?c1:c2;
}
Chain res=null;//返回的头结点
if (c1.value<c2.value) {
res=c1;
res.next= mergeMutiChainOfTwo2(c1.next, c2);
}else {
res=c2;
res.next= mergeMutiChainOfTwo2(c1, c2.next);
}
return res;
}
//合并两个有序链表 方法三 递归
public static Chain mergeMutiChainOfTwo3(Chain c1,Chain c2) {
if (c1==null||c2==null) {
return c2==null?c1:c2;
}
if (c1.value<c2.value) {
c1.next= mergeMutiChainOfTwo3(c1.next, c2);
return c1;
}else {
c2.next=mergeMutiChainOfTwo3(c1, c2.next);
return c2;
}
}
//合并K个链表
public static Chain mergeMutiChainOfK(List<Chain> list,int start,int end) {
if (list==null||list.size()==0) {
return null;
}
if (start<end) {
int middle=(start+end)/2;
Chain c1=mergeMutiChainOfK(list, start, middle);
Chain c2=mergeMutiChainOfK(list, middle+1,end);
return mergeMutiChainOfTwo3(c1, c2);
}
return list.get(start);
}