Search code examples
javanullpointerexceptionlinked-listdeque

NullPointerException for Dequeue object class


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

}

Solution

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