【问题标题】:I'm implementing a deque using singly linked list in Java. My addLast() is not working我正在使用 Java 中的单链表实现双端队列。我的 addLast() 不工作
【发布时间】:2017-03-27 14:51:14
【问题描述】:

我正在使用 Java 中的单链表实现双端队列。我的addFirst() 函数工作正常,但addLast() 不工作。

每当我拨打addLast() 时,都会收到以下错误消息:

java.lang.NullPointerException

【问题讨论】:

  • NullPointerException 中包含的完整堆栈跟踪是什么?您的错误控制台会告诉您在哪一行引发了异常,以及当时调用的所有内容?另外,请在提问时将代码发布为文本,而不是屏幕截图。
  • 不要将您的代码发布为图片,请发布代码!
  • 调用 addLast 的代码在哪里?
  • 来自控制台的错误消息显示 old_last.next 为空。然后我不知道如何修改这个函数,以便它成功地将一个项目附加到一个双端队列的后面。
  • 请添加invoke addLast方法

标签: java linked-list stack queue deque


【解决方案1】:

一开始你的最后一个是null

当您将其分配给old_last 时,old_last 也为空。

所以当你调用old_last.next 时,NPE 会抛出。

【讨论】:

  • 是的,这正是问题所在。那你知道怎么解决吗?我知道你可以用一个单链表来实现一个队列,并且为一个队列实现 addLast() 的代码和我的完全一样。那么为什么相同的实现适用于队列而不适用于双端队列?
  • 查看codereview.stackexchange.com/questions/56361/…了解如何实现双端队列。
【解决方案2】:

为您的 Node 类提供一个构造函数将有助于使您的代码保持简短和干燥:

private class Node {
  Item item;
  Node next;
  private Node(Item item, Node next) {
    if (item == null) throw new NullPointerException();
// 'this' refers to the created instance and helps distinguish the field from the param
    this.item = item;  
    this.next = next;
  }
}

public void addFirst(Item item) {
  // creates a new Node before first so to speak and then repoints first to this node 
  first = new Node(item, first);   
  if (num_elements==0) last = first;
  num_elements++;
}

public void addLast(Item item) {
  if (num_elements == 0) {  
    // this will deal with the case (last==null) which causes the NPE
    addFirst(item);
    return;
  }
  last.next = new Node(item, null);
  last = last.next;
  num_elements++;
}

除此之外,单链表并不是双端队列的理想数据结构。两端加的是O(1),后面去掉的是O(N)

【讨论】:

  • 有效!!太感谢了。但我对 Java 很陌生,所以我不太了解它是如何工作的。例如,我对类构造函数感到困惑,尤其是在这种情况下的关键字“this”。另外,对于 addFirst() 函数,为什么你只做 first = new Node(item, first) 而不是 first.next = new Node(item, first)?
  • 我添加了一些 cmets 来阐明这些点。 first.next = new Node(item, first) 会创建一个循环链接结构,不会。 first 指的是新节点,新节点首先指代。此外,first 在这里可能为空,因此可能会失败。
  • 非常感谢!!另外,你能帮我解决另一个 Java Comparator 问题吗?我已经被困在这个问题上很长时间了!谢谢! stackoverflow.com/questions/40622793/…
猜你喜欢
  • 2017-11-25
  • 1970-01-01
  • 2016-08-18
  • 2011-06-23
  • 2012-05-15
  • 2017-10-07
  • 2021-10-30
  • 2013-03-10
  • 2017-02-28
相关资源
最近更新 更多