Queue
Queue follow first in first out strategy which practically means that as a value is added in front a value is removed from the bottom or vice versa.
Application->
1. In resource scheduling
2. Data transfer
Let's see how a queue works with a simple example-
class Queue{
public:
int front, rear, size;
unsigned capacity;
int* array;
};
Queue *createqueue(unsigned capacity)
{
Queue* q= new Queue();
q->capacity= capacity;
q->front= q->size=0;
q->rear=capacity-1;
q->array= new int[q->capacity];
return q;
}
//queue becomes full when size=capacity
int full(Queue* q)
{
return(q->size==q->capacity)
}
//queue becomes empty when size=0
int empty(Queue* q)
{
return(q->size=0);
}
//add item to a queue
void enqueue(Queue* q, int item)
{
if(full(q))
return;
q->rear= (q->rear+1) % q->capacity;
q->array[q->rear]=item; //insertion at the end
q->size= q->size+1;
cout<<item;
}
//remove item from queue
void dequeue(Queue* q)
{
if(empty(q))
cout<<"Queue is empty";
return;
int item= q->array[q->front]; //puts item in the front of the queue
q->front=(q->front+1)% q->capacity; //reduced capacity of front
q->size=q->size-1; //reduce size by 1
return item;
}
//get front of queue
int front(Queue* q)
{
if(empty(q))
return;
return q->array[q->front];
}
//get rear of queue
int rear(Queue* q)
{
if(empty(q))
return;
return q->array[q->rear];
}