ZBLOG

package 线性表; public class CirDoublelyLists { public DoubleNode head; public DoubleNode rear; public CirDoublelyLists() { this.head=new DoubleNode(); this.head.prev=this.head; this.head.next=this.he...

出现空指针异常的原因是在insert()方法中未对空链表进行处理。为了修复这个问题,你可以在插入节点之前,先检查链表是否为空,若为空,则将头结点和尾结点都指向新节点即可。

具体修改如下:

public DoubleNode<T> insert(int i, T x) {
    if (x == null)
        return null;
    if (isEmpty()) { // 链表为空时的处理
        DoubleNode<T> q = new DoubleNode<T>(x, head, head);
        head.next = q;
        head.prev = q;
        return q;
    }
    DoubleNode<T> front = this.head;
    for (int j = 0; front.next != this.head && j < i; j++)
        front = front.next;
    DoubleNode<T> q = new DoubleNode<T>(x, front, front.next);
    front.next.prev = q;
    front.next = q;
    return q;
}

public boolean isEmpty() {
    return head.next == head && head.prev == head;
}

通过以上修改,当链表为空时,在调用insert()方法插入第一个节点时就不会报空指针异常了。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=8678

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?