双向链表的定序插入

双向链表的定序插入

代码实现:

我的代码:

  public void addByteOrder(Hero hero){
        Hero temp = head;
        if(head.next == null){
            temp.next = hero;
            hero.pre = temp;
        }
        boolean isFlag = true;
        while (true){
            if(temp.next.no == hero.no){
                isFlag = false;
                break;
            }

            if(temp.next == null){
                temp.next = hero;
                hero.pre = temp;
                break;
            }
            if(temp.next.no > hero.no){
                break;
            }

            temp = temp.next;
        }
        if (isFlag){
            hero.next = temp.next;
            temp.next.pre = hero;
            temp.pre = temp;
            temp.next = hero;
        }else{
            System.out.println("你所插入的序号已经存在");
        }
    }
问题:

如果我添加的是最后一个节点,会不会出现空指针异常?单链表不会,即使最后一个节点为空,也不涉及调用空指针的内容,仅仅是作为一个地址。但这里不一样,涉及调用节点的前继指针,所以会出现空指针异常。

运行异常:

异常代码

分析:

程序运行现如死循环,当要添加的节点为尾节点时,连续两次操作尾节点,致使最后一个添加的元素自我循环,调不出来

修改后的代码:

public void addByteOrder(Hero hero){
    Hero temp = head;
    if(head.next == null){
        temp.next = hero;
        hero.pre = temp;
    }
    int isFlag = 0;
    while (true){
        if(temp.next == null){
            temp.next = hero;
            hero.pre = temp;
            break;
        }
        if(temp.next.no == hero.no){
            isFlag = 2;
            break;
        }
        if(temp.next.no > hero.no){
            isFlag = 1;
            break;
        }

        temp = temp.next;
    }
    if (isFlag == 2){
        hero.next = temp.next;
        temp.next.pre = hero;
        hero.pre = temp;
        temp.next = hero;
    }else if(isFlag == 1){
        System.out.println("你所插入的序号已经存在");
    }
}
解决:

如果不单列出来尾指针的特殊情况,确实会出现空指针情况,但如果单列了尾指针又没有与常规情况加以区分,那么就会连续操作两次添加的元素,造成自我循环封闭

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值