Skip to content
Advertisement

Create the Queue class and print the element inside from first to last

I currently have an assignment that I need to create my own Queue class and methods such as enqueue(), dequeue(), and display the elements from first to last. This is what I did so far:

The node class:

JavaScript

This is my queue class:

JavaScript

And the main class for testing:

JavaScript

So what I want the output to be is

JavaScript

However, my output is :

JavaScript

Can you guys have a look, I think it must be something to do with the displayQueue() method but I don’t know how to fix it, can you guys help me. Thanks a lot

Advertisement

Answer

I believe your enqueue logic for the most part is correct in the sense that you are adding new elements at the end of the queue and resetting this.rear to the new element added. However, you should make your displayQueue method recursive so that you can follow the FIFO, first-in-first-out, principle and iterate through the queue from the start to the end instead of what you have now, which is iterating through the queue from the end to the start. The reason that recursion is recommended here is that you structured your queue currently in a way where there is only a one-way route from the last node to the first node and not vice versa, so your base condition for the recursive method can be when the node your iterating on is null. At that point you can start printing out nodes as you back-track from the start to the end of the queue. Note that the next pointer of the node you are iterating on will be null when that node you are iterating on is the start of the queue. Here’s what a recursive displayQueue method would look like with a helper function,

JavaScript

I chose to use a recursive helper function because you should still use the main outside displayQueue function to check if the queue is empty before deciding whether or not to iterate through the queue.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement