class Node{
int val;
Node next;
Node(int val){this.val=val;}
}
public class Combine{
public static Node SortList(Node l1,Node l2){
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
Node cur1=l1;
Node cur2=l2;
Node result=null;
Node last=null;
while(cur1!=null&&cur2!=null){
if(cur1.val<cur2.val){
Node next=cur1.next;
if(result==null){
result=cur1;
}
else{
last.next=cur1;
}
last=cur1;
cur1=next;
}
else{
Node next=cur2.next;
if(result==null){
result=cur2;
}
else{
last.next=cur2;
}
last=cur2;
cur2=next;
}
}
if(cur1!=null){
last.next=cur1;
}
else{
last.next=cur2;
}
return result;
}
public static void main(String[] args) {
Node n1=new Node(1);
Node n2=new Node(2);
Node n3=new Node(6);
Node n4=new Node(9);
Node n5=new Node(20);
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n5;
Node n6=new Node(3);
Node n7=new Node(5);
Node n8=new Node(10);
Node n9=new Node(11);
Node n10=new Node(23);
n6.next=n7;
n7.next=n8;
n8.next=n9;
n9.next=n10;
Combine s=new Combine();
Node result=s.SortList(n1,n6);
while (result != null) {
System.out.print(result.val + " ");
result = result.next;
}
}
}
【Java】实现两个有序链的合并(合并后仍有序)
最新推荐文章于 2022-11-25 21:18:52 发布