有序双链表合并

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==========");

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值