public static Node Merge(Node list1,Node list2) {
if(list1==null)return list2;
if(list2==null)return list1;
Node pre1=null;
Node nhead=new Node(-1);
nhead.next=list1;
pre1=nhead;
Node p1=list1;
Node p2=list2;
Node next2=null;
while(p1!=null&&p2!=null){
while(p1!=null&&p1.val<=p2.val){
pre1=p1;
p1=p1.next;
}
if(p2!=null){
next2=p2.next;//特别容易出错,
p2.next=p1;
pre1.next=p2;
p2=next2;
//next2=p2.next;若写在这,当p2位空,next2则为空的next出现空指针异常!!!特别注意
}
}
if(p2!=null){
pre1.next=p2;
}
return list1;
}
把两个有序链表合并为一个有序链表(注意空指针异常!)
最新推荐文章于 2024-05-02 17:15:17 发布