addLast – 双向循环链表 – 空指针异常

huangapple 未分类评论43阅读模式
英文:

addLast - doubly circular linkedlist - NullPointerException

问题

在双向循环链表末尾插入元素的方法是什么?为什么我运行这段代码时会出现“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);
    }
}
英文:

How do you insert an item at the end of a doubly circular linked list? Why do I have a NullPointerException when I run this?

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

      }
      }

答案1

得分: 0

代码设置了新节点的引用,但没有更新列表中的现有引用。修正后的内容如下:

if (isEmpty()) { // 假设如果为空,head == null
    head = new Episode(title, length, head, head);
    head.next = head; // 修正
    head.prev = head; // 修正
} else {
    Episode last = head.prev;
    Episode new_episode = new Episode(title, length, head, last);
    last.next = new_episode; // 修正
    head.prev = new_episode; // 修正
}
英文:

The code sets the new node's references, but doesn't update the existing references in the list. Fixed noted in commments:

    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
    }

huangapple
  • 本文由 发表于 2020年4月7日 20:59:07
  • 转载请务必保留本文链接:https://java.coder-hub.com/61080596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定