Home > database >  Linked Queue in Java not enqueuing properly
Linked Queue in Java not enqueuing properly

Time:12-19

I have this LinkedQueue.java class which implements from QueueInterface.java

When I try to enqueue data, it does something weird, the 1st value to enqueue is somewhat ignored, and then when running the 2nd enqueue it enqueues the 1st value. When running the 3rd enqueue it enqueues the 2nd value. Finally, running the 4th enqueue enqueues the 3rd value, and the final 4th value is never enqueued.

Here is a screenshot of my output

Here is the code which tests the code (enqueues and dequeues):

public class QueueTest3
{   public static void main(String[] args)
    {   QueueInterface<Integer> queue = new LinkedQueue<Integer>();
        
        //use enqueue method
        System.out.println("\nenqueuing -1");
        queue.enqueue(-1);
        queue.display();
        System.out.println("\nenqueuing 0");
        queue.enqueue(0);
        queue.display();
        System.out.println("\nenqueuing 1");
        queue.enqueue(1);
        queue.display();
        System.out.println("\nenqueuing 5");
        queue.enqueue(5);
        queue.display();
        
        while (!(queue.isEmpty()))
        {  //remove head element
           int removedItem = queue.dequeue();
           System.out.printf("%n%d dequeued%n", removedItem);
           queue.display();
        }
    }
}

Here is my enqueue method.

 public void enqueue(T newEntry)
   { 
    Node newNode = new Node(newEntry, null);

    if (lastNode == null){
      firstNode = lastNode = newNode;
      return;
    }
    lastNode.setNextNode(newNode);
    lastNode = newNode;
    numNodes  ;
    }

I'm stumped, I have rewritten the enqueue code many times. It went from actually giving out errors, to this. How can I solve this?

CodePudding user response:

You forgot to increment the numNodes in enqueue if it is the first node:

public void enqueue(T newEntry) {
        Node newNode = new Node(newEntry, null);

        if (lastNode == null) {
            firstNode = lastNode = newNode;
            numNodes  ;
            return;
        }
        lastNode.setNextNode(newNode);
        lastNode = newNode;
        numNodes  ;
    }

or slightly cleaner imo

public void enqueue(T newEntry) {
        Node newNode = new Node(newEntry, null);
        numNodes  ;
        if (lastNode == null) {
            firstNode = lastNode = newNode;
            return;
        }
        lastNode.setNextNode(newNode);
        lastNode = newNode;
    }
  • Related