Note: Assuming a queue can grow dynamically we are not considering the overflow condition
Now let’s see an example of queue class using an array:-
As in the above definition we have created a skeleton of a queue class which contains a constructor in which we declare an array to implement queue. Hence, with the creation of an object of a queue class this constructor would be called automatically and the array will be declared
Let’s implement each of these functions:
- enqueue() – Adds an element to the queue
// enqueue function
// adding element to the queue
This function adds an element at the rear of a queue. We have used push() method of array to add an element at the end of the queue.
- dequeue() – Removes an element from the queue
// dequeue function
// removing element from the queue
// returns underflow when called
// on empty queue
This function removes an element from the front of a queue . We have used shift method of an array to remove an element from the queue.
- front() – returns the front element of the queue
// front function
// returns the Front element of
// the queue without removing it.
"No elements in Queue"
This function returns the front element of the queue. We simply return the 0th element of an array to get the front of a queue.
Let’s declare some helper method which is quite useful while working with the queue.
- isEmpty() – Returns true if the queue is empty
// isEmpty function
// return true if the queue is empty.
In this function we have used the length property of an array and if the array length is 0 then the queue is empty.
- printQueue()– Returns all the elements of an queue.
// printQueue function
var str =
(var i =
; i <
In this method we concatenate all the elements of the queue in a string and return the string
Note: Different helper method can be declared in Queue class as per the requirement.
Now let’s use the queue class and its different method described above
Now once we are done with the implementation of Queue class we can use it different applications.
In this problem we generate different binary numbers from 1 to n.
This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.