Queue is a linear data structure, in which elements are inserted from one end called the rear, and the removal of existing elements takes place from the other end called front. Queue data structure utilizes both its ends, unlike the stack data structure.
Queue follows FIFO (First In First Out) principle, which means the first inserted element is removed first.
A real-life example of the queue data structure is a line of people standing in a bank, the person who entered first gets their work done first, and hence leaves first.
Insertion in the queue is done at the rear end, and the process is called Enqueue.
The process of removal of an element from the queue is called Dequeue, which is done from the front end.
Data
front and rear are index pointers.
class Queue{
int arr[50]
int front, rear;
int size;
};
Constructor to initialize size, front and rear :
Queue(int n)
{
front = -1;
rear = -1;
size =n;
}
The following are the different types of queues :
bool isFull()
{
if (rear == SIZE - 1)
return true;
return false;
}
bool isEmpty()
{
if (front == rear)
return true
return false;
}
note : First element is at index 0, but front remains at -1.
void enqueue(int x)
{
if(rear==size-1)
print("Queue Full");
else
{
rear++;
arr[rear]=x;
}
}
Time complexity : O(1)
note: front is kept before the 1st element and not on it.
int dequeue()
{
int x=-1;
if(front==rear)
print("Empty Queue");
else
{
x=arr[front+1];
front++;
}
return x;
}
Time complexity : O(1)
Displaying a queue
void Queue :: display()
{
int i;
for( i = front; i <= rear; i++)
{
print(arr[i])
}
}
After performing enqueuing and dequeuing several times, the size of the queue gets reduced. The indices 0,1,2,3 can not be used until after the queue’s indices are reset after removal of all the elements. This can be seen below :
After the last element is removed, the front is at the rear and, the rear is at (size-1). This leads to the queue being both Full and Empty at the same time, which is wrong. The blank spaces cannot be utilized.
Solution: