A Queue is a linear data structure, following a particular order FIFO (First In First Out) where we can insert elements at one end and remove elements in the other end just like a human queue from the supermarket or railways ticket booking counters.
In the previous article, we saw how Queue interface in java collections works, its implementation and how we can implement queues with LinkedList
, Priority Queues
and ArrayDequeues
, its methods, and syntax.
Some of the many applications of Queues are :
- A single resource is served among multiple consumers in their arrival order.
- It provides synchronization facilities between slow and fast devices.
- It is used in operating systems as job schedulers, semaphores, and buffers.
- It is also used in network queues, mailing queues, etc
Implementation Queues Using Arrays
class Queue
{
int size, capacity;
int arr [];
Queue( int c )
{
capacity = c;
size = 0;
arr = new int[ capacity ];
}
boolean isFull()
{
return( size == capacity);
}
boolean isEmpty()
{
return( size == 0 );
}
void enqueue( int x )
{
if( isFull() ) return;
arr[ size ] = x;
size++;
}
void dequeue()
{
if( isEmpty() ) return;
for( int i = 0; i < size - 1; i++)
arr [ i ] = arr [ i+1 ];
size--;
void getFront()
{
if( isEmpty() ) return -1;
else
return 0;
}
void getRear()
{
if( isEmpty()) return -1;
else
return size - 1;
}
class Queue
{
int size, capacity;
int arr [];
Queue( int c )
{
capacity = c;
size = 0;
arr = new int[ capacity ];
}
boolean isFull()
{
return( size == capacity);
}
boolean isEmpty()
{
return( size == 0 );
}
void enqueue( int x )
{
if( isFull() ) return;
arr[ size ] = x;
size++;
}
void dequeue()
{
if( isEmpty() ) return;
for( int i = 0; i < size - 1; i++)
arr [ i ] = arr [ i+1 ];
size--;
void getFront()
{
if( isEmpty() ) return -1;
else
return 0;
}
void getRear()
{
if( isEmpty()) return -1;
else
return size - 1;
}
This program implements 6 functions required for the functioning of queue in Java.
- isFull() : This function checks if the queue is full or not.
- isEmpty() : This function checks if the queue is empty or not.
- enqueue() : This function enters an element at the back of the queue.
- dequeue() : This function deletes an element from the front of the queue.
- getFront() : This function get the front most element of the queue.
- getRear() : This function gets the rear most element of the queue.
Worst case Time Complexity of this queue is O( n ).
This was a basic implementation of a queue using array, an efficient implementation of queue requires and circular array.