gpt4 book ai didi

java - Dequeue 对象类的 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 07:26:34 26 4
gpt4 key购买 nike

我正在尝试创建一个链接列表出队类,它接受头部和尾部的节点。一切都编译得很好,但是当我运行它时,我得到一个 NullPointerException。它指向我的内部 QueueNode 类,但我不确定如何修复它。有什么想法吗?谢谢!

public class LinkedDequeue 
{
private QueueNode front; //index of current front element
private QueueNode rear; //index of current rear element
private int count; //current # of elements

class QueueNode
{
private Object data;
private QueueNode link;
}

public LinkedDequeue ()
{
front = rear = null;
count = 0;
}

public void headAdd (Object o)
{
if (isEmpty())
{
front.data = o;
rear.data = o;
front.link = rear;
rear.link = null;
}
else
{
QueueNode temp = new QueueNode();
temp.data = o;
front.data = temp;
front.link = front;
}

count++;
}

public boolean isEmpty()
{
return (count == 0);
}

public static void main (String [] args)
{
LinkedDequeue list = new LinkedDequeue ();

list.headAdd ("test?");

System.out.println (list.toString());
}

}

最佳答案

我认为问题在于,当您创建列表时,您的 front 和 back == null ,然后尝试编辑 front.data (null 没有数据字段)。因此,您应该在代码中添加这些行:

  if (isEmpty()) 
{
front = new QueueNode();
rear = new QueueNode();
front.data = o;
rear.data = o;
front.link = rear;
rear.link = null;
}

关于java - Dequeue 对象类的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23621342/

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