合并k个升序链表,可以两个合并一个,然后合并成新的链表之后,新链表与链表数组中的下一个链表继续合并。
Java中没有结构体。
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode res=null;
int len=lists.length;
for(int i=0;i<len;i++){
res=mergeTwo(res,lists[i]);
}
return res;
}
public ListNode mergeTwo(ListNode la,ListNode lb){
if(la==null&&lb!=null){
return lb;
}
else if(la==null && lb==null){
return null;
}
else if(la!=null && lb==null){
return la;
}
ListNode p=la,q=lb;
ListNode head=new ListNode(0);
ListNode r=head;
while(p!=null&&q!=null){
if(p.val<q.val){
r.next=p;
r=p;
p=p.next;
}else{
r.next=q;
r=q;
q=q.next;
}
}
if(p==null){
r.next=q;
}else{
r.next=p;
}
return head.next;
}
}