public static class ListNode {
public int val;
public ListNode next;
public ListNode(int v){
this.next=null;
this.val=v;
}
}
//两个有序列表的合并
//链表A 1 3 5 7 9
//链表B 1 2 4 6
//合并以后是 1 1 2 3 4 5 6 7 9
@Test
void contextLoads(){
//思路 先比较第一列 谁大谁小 小的先开始
ListNode aNode=new ListNode(1);
aNode.next=new ListNode(3);
aNode.next.next=new ListNode(5);
aNode.next.next.next=new ListNode(7);
aNode.next.next.next.next=new ListNode(8);
ListNode bNode=new ListNode(1);
bNode.next=new ListNode(2);
bNode.next.next=new ListNode(4);
bNode.next.next.next=new ListNode(6);
ListNode head= aNode.val<=bNode.val?aNode:bNode;//A
ListNode cur1=head.next;//3
ListNode cur2=head==aNode?bNode:aNode;//B
ListNode pre=head;//A
while (cur1 != null && cur2 != null) {
if (cur1.val <= cur2.val) {//A.3 vs B.1
pre.next = cur1;
cur1 = cur1.next;
} else {
pre.next = cur2;//1
cur2 = cur2.next;//指向2
}
pre = pre.next;//指向3
}
pre.next = cur1 != null ? cur1 : cur2;
System.out.println("===========输出 head==========");
}
|