0

I'm a beginning programmer working on a from-scratch queue implementation, and for some reason I've got an off-by-one error. Here's my class:

class Queue
{
   // pointer to first node in stack
   public Node oldest;
   public Node youngest;
   public int queueSize = 0;

   // constructor
   public Queue(){
       oldest = null;
       youngest = null;
       queueSize = 0;
}

   public boolean isEmpty() {
       return oldest == null;
   }

   public boolean add(Node newNode){ 

   if(isEmpty()){
       oldest = newNode;
   }else{
       newNode.next = youngest;
       oldest.next = youngest;
       youngest = newNode;
       }

       return true;
   }


   public Node remove(){
       Node temp;
       temp = oldest;
       if( oldest != null){
           oldest = oldest.next;
           temp.next = null;
       }
       queueSize--;
       return temp;
   }

   public void showQueue(){
       Node p;    
       for(p = oldest; p != null; p = p.next){
         p.toString();
       }
   }
}

If I fill the Queue using a loop, and then do showQueue(), I'm always one less than I should be. For example, this, from my main:

      // build the queue
      for (int k = 0; k < 5; k++)
      {
         node1 = new Node();
         queue2.add(node1);
      }

      //show the stack
      queue2.showQueue();

gives the result

(Node) (Node) (Node) (Node)

or only four nodes. What's going on here?

Thanks in advance.

2
  • Think I got it. Went with the logic here in the "enqueue" method in this post, and was able to get rid of the error: stackoverflow.com/questions/15015516/… Still not understanding why my code didn't work, so I'd appreciate any explanations! Commented Nov 10, 2014 at 17:52
  • I'm not sure what youngest is supposed to be. You should probably not have this field. And queueSize is decremented, but never incremented. Since oldest is the first node in the queue, and you need a comment to make that clear, why don't you name it firstNode? Commented Nov 10, 2014 at 18:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.