Queue is a data structure which operates on FIFO(first in first out) principle.The element enqueued first,dequeues first.
front keeps track of front element in queue.
rear keeps track of last element in queue.
front keeps track of front element in queue.
rear keeps track of last element in queue.
Lets see how we can implement a queue using an array.
Declaring the queue structure
typedef struct
{
int front,rear,arr[SIZE];
}queue;
Initialize
front = rear = -1
Check empty queue
front == -1
OR
rear == -1
Check full queue
q.rear == (SIZE-1)
Enqueue
if queue is empty
increment front and rear.Enqueue element at rear position.
else
increment rear.Enqueue element at rear position.
void enqueue(int element)
{
if(isFull())
{
printf("\nQueue is full");
return;
}
if(isEmpty())
q.front++;
q.arr[++q.rear] = element;
}
Dequeue
Store front element in element.
if last element is left
initialize the queue
else
increment front
return element
int dequeue()
{
int element = q.arr[q.front];
if(isEmpty())
{
printf("\nQueue is empty.Can't dequeue");
return -1;
}
else
{
if(q.front == q.rear) //last element in queue
init();
else
q.front++;
return element;
}
}
Helpful but it can be explained better.
ReplyDelete