Domanda

I'm trying to create a Linked List dequeue class that accepts nodes at the head as well as rear. Everything compiles fine, but when I go to run it I get a NullPointerException. It's pointing to my inner QueueNode class, but I'm not sure how to go about fixing it. Any thoughts? Thanks!

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());
   }

}
È stato utile?

Soluzione 2

You have to always create a new QueueNode() when you add elements to your LinkedDequeue(). Change addHead() method to as follows -

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++;
}

Altri suggerimenti

I believe that the problem is that your front and rear == null when you create the list and after that try to edit front.data (null does not have a data field). Therefore you should add these lines inside your code:

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

change your constructor to below:

    public LinkedDequeue ()
        {
            front = new QueueNode();
            rear = new QueueNode();
            count = 0;
        }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top