Dequeue对象类的NullPointerException

时间:2014-05-13 01:12:01

标签: java nullpointerexception linked-list deque

我正在尝试创建一个Linked List dequeue类,它接受头部和后部的节点。一切都编译得很好,但是当我去运行它时,我得到一个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());
   }

}

3 个答案:

答案 0 :(得分:3)

我认为问题是你创建列表时前后== null,然后尝试编辑front.data(null没有数据字段)。因此,您应该在代码中添加以下行:

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

答案 1 :(得分:2)

将构造函数更改为:

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

答案 2 :(得分:2)

在向LinkedDequeue()添加元素时,必须始终创建新的QueueNode()。 将addHead()方法更改为如下 -

public void headAdd(Object o) {
    QueueNode temp = new QueueNode();
    temp.data = o;

    if (isEmpty()) {
        front = temp;
        rear = front;
        front.link = null;
        rear.link = null;
    } else {
        temp.link = front; 
        front = temp;
    }

    count++;
}