【问题标题】:How to debug my Java linked-list queue?如何调试我的 Java 链表队列?
【发布时间】:2017-02-10 06:35:37
【问题描述】:

我对 C++ 中的链表基本上没有任何问题,但出于某种原因,这对我来说很重要。我使用提供的包中的其他类打印了一个节点,但随着我的继续,我一直在撞墙。

下面的代码是乱七八糟的,因为我在修补。我只是不知道从这里去哪里。到目前为止,这是一个空指针异常。

仅供参考:poll() 只是移除当前头部并返回它,offer() 正在添加到后面。到目前为止,offer 方法中的oldLast.next = last 是例外。

我不是要求任何人彻底解决这个问题。我只需要一些提示来进步。

public class FIFOQueue implements Queue {

//put your name as the value of the signature.
String signature = "name";

Node head = new Node(null);
Node pointer = head;
Node first;
Node last;
Node prev;
Node curr;

class Node {
    Process process;
    Node next;


    Node(Process p) {
        this.process = p;
        this.next = null;
    }

}

@Override
public void offer(Process p) {


    if(head == null)
    {
        head = new Node(p);
        first = head;
        last = head;

    }

    else
    {

        Node oldLast = last;
        Node newNode = new Node(p);

        last = newNode;
        oldLast.next = last;


    }



}


@Override
public Process poll() {


    if(isEmpty())
        throw new NoSuchElementException();

    Node oldPointer = first;

    first = first.next;
    head = first;


        return oldPointer.process;
}

@Override
public boolean isEmpty() {

return head == null;

}

@Override
public String getSignature() {
    return signature;
}

}

【问题讨论】:

  • 您需要更具体。如果您说“我在第 15 行收到ArrayIndexOutOfBoundsException”,那么您更有可能得到答案,而不是“事情不正常,我希望您能帮助我”。
  • 真的,对不起。到目前为止,我从“ oldLast.next = last;”中得到了例外在报价功能中。
  • 如果您从那里获得NPE,那么您的oldLast 为空。无论何时收到NullPointerException,请参阅stackoverflow.com/questions/218384/…
  • 会的。谢谢您的帮助!不过,我会假设代码存在更多问题。

标签: java linked-list queue fifo


【解决方案1】:

我认为你的核心问题在这里:

Node prev;
Node curr;

这些让你感到困惑。删除它们。

  1. Node prev; - 这应该在 Node 类中。
  2. Node curr; - 这应该是局部变量,而不是实例变量。

还有

Node head = new Node(null);

不与

凝胶
if(head == null)
{
    head = new Node(p);

要么使head == null 表示列表为空或其他 - 但要保持一致。

【讨论】:

  • 我相信我还没有使用过。这是一项正在进行的工作,我正在修补它以查看是否有效果。使用这两个变量是我的下一步行动。到目前为止,我只声明了它们。
  • 醒来看到你的编辑。谢谢你回到我身旁。我有点困惑这两个怎么不排队。 head 应该保持为空吗?
  • 您的评论基本上帮助我解决了我的问题。发现最初的检查应该是查看节点中的实际数据是否为空,而不是检查整个节点是否为空。谢谢!
【解决方案2】:

(代表 OP 发布)

public void offer(Process p) {


    if(head.process == null)
    {
        head = new Node(p);
        first = head;
        last = head;
    }


        last.next = new Node(p);
        last = last.next;

}

这解决了我的问题。不敢相信我让这让我感到困惑。

【讨论】:

    猜你喜欢
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    相关资源
    最近更新 更多