gpt4 book ai didi

java - addLast - 双循环链表 - NullPointerException

转载 作者:行者123 更新时间:2023-12-01 17:33:28 24 4
gpt4 key购买 nike

如何在双向循环链表的末尾插入一个项目?为什么我运行时会出现 NullPointerException

   public void addLast( String title, double length ){

if( isEmpty()){
head = new Episode(title, length, head, head);
}else{
Episode last = head.prev;
Episode new_episode = new Episode(title, length, head, last);

}
}

最佳答案

代码设置新节点的引用,但不会更新列表中的现有引用。已修复评论中指出的问题:

    if( isEmpty()){            // assuming if empty, head == null
head = new Episode(title, length, head, head);
head.next = head; // fix
head.prev = head; // fix
} else {
Episode last = head.prev;
Episode new_episode = new Episode(title, length, head, last);
last.next = new_episode; // fix
head.prev = new_episode; // fix
}

关于java - addLast - 双循环链表 - NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61080596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com