【问题标题】:addLast - doubly circular linkedlist - NullPointerExceptionaddLast - 双循环链表 - NullPointerException
【发布时间】:2020-04-07 12:59:07
【问题描述】:

如何在双循环链表的末尾插入一个项目?为什么我运行这个时会有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);

      }
      }

【问题讨论】:

  • 能否请您保留您的代码?问题是,head 对象仅在 if 块的一个条件下创建。看不到它是否被设置在其他地方
  • head 在构造器中创建

标签: java linked-list insert doubly-linked-list circular-list


【解决方案1】:

代码设置新节点的引用,但不更新列表中的现有引用。已在评论中注明:

    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
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    相关资源
    最近更新 更多