合并2个有序单链表,合并后仍然有序主要合并代码(还有cur1.id==cur2.id的情况漏掉了)

public HeroNode mergeSingleLinkedList(HeroNode head1,HeroNode head2){
if(head1.nextnull || head2.nextnull){
System.out.println(“无法合并,请仔细检查传入的链表是否为空!”);
return null;
}
HeroNode cur1 = head1.next;
HeroNode cur2 = head2.next;
HeroNode next = null;
HeroNode newHead = new HeroNode();
while(true){
if(cur1null && cur2null){
return newHeadt;//只上传方法并返回一个头,测试代码自己写吧,不完善的地方欢迎大家留言指点!
}
if(cur1null && cur2!=null){
next = cur2.next;
cur2.next = newHead.next;
newHead.next = cur2;
cur2 = next;
}
if(cur2
null && cur1!=null){
next = cur1.next;
cur1.next = newHead.next;
newHead.next = cur1;
cur1 = next;
}
if(cur1 != null && cur2!= null && cur1.id < cur2.id){
// 2 9 11
// 3 4 5 6 7
next = cur1.next;
cur1.next = newHead.next;
newHead.next = cur1;
cur1 = next;
}else if(cur1 != null && cur2!= null && cur1.id > cur2.id){ //这里逻辑关系一定要写上 “cur1 != null && cur2!= null &&”,害我找了1个小时的错(甚至更久)
next = cur2.next;
cur2.next = newHead.next;
newHead.next = cur2;
cur2 = next;
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值