21合并两个有序链表
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
if(l2.val<l1.val){
ListNode t=l1;
l1=l2;
l2=t;
}
ListNode p1=l1;
l1=l1.next;
ListNode ret=l1;
while(l1!=null && l2!=null){
if( l2.val<l1.val){
p1.next=l2;
l2=l2.next;
}else{
p1.next=l1;
l1=l1.next;
}
p1=p1.next;
}
if(l1==null){
p1.next=l2;
}
if(l2==null){
p1.next=l1;
}
return ret;
}
哈哈
合并K个有序链表,这个还可以分冶
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public ListNode mergeKLists(ListNode[] lists) {
int len=lists.length;
if(len==0){
return null;//这个并不友好
}
ListNode ret=new ListNode(0);
ret.next=lists[0];
for(int i=1;i<len;i++){
ListNode list2=lists[i];
ListNode list1=ret.next;
ListNode temp=new ListNode(0);
ret=temp;
while(list2!=null && list1!=null){
if( list2.val>=list1.val ) {
temp.next=list1;
list1=list1.next;
}else{
temp.next=list2;
list2=list2.next;
}
temp=temp.next;
}
if(list1==null){
temp.next=list2;
}
if(list2==null){
temp.next=list1;
}
}
return ret.next;
}
哈哈