queue in data structure using c


Ø  Queue –
·        Queue is an abstract data structure, it is similar to Stacks.
·        Unlike stacks, a queue is open at both its ends.
·        One end is always used to insert data (enqueue) and the other is used to remove data (dequeue).
·        Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first.
·        In queue, we always dequeue (or access) data, pointed by front pointer and while enqueing (or storing) data in the queue we take help of rear pointer.

·        A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits first.

·        More real-world examples can be seen as queues at the ticket windows and bus-stops

 

#include<stdio.h>
#include<conio.h>
#define MAX 10 // Changing this value will change length of array
int queue[MAX];
int front = -1, rear = -1;
void insert();
void delete_element();
void peek();
void display();
main()
{
int option, val;
do
{
printf("\n\n ***** MAIN MENU *****");
printf("\n 1. Insert an element");
printf("\n 2. Delete an element");
printf("\n 3. Peek");
printf("\n 4. Display the queue");
printf("\n 5. EXIT");
printf("\n Enter your option :");
scanf("%d", &option);
switch(option)
{
case 1:
insert();
break;
case 2:
delete_element();
break;
case 3:
peek();
break;
case 4:
display();
break;
}
}while(option != 5);
getch();
}
void insert()
{
int num;
printf("\n Enter the number to be inserted in the queue :");
scanf("%d", &num);
if(rear == MAX-1)
printf("\n OVERFLOW");
else if(front == -1 && rear == -1)
front = rear = 0;
else
rear++;
queue[rear] = num;
}
void delete_element()
{
int val;
if(front == -1 || front>rear)
{
printf("\n UNDERFLOW");
}
else
{
val = queue[front];
front++;
if(front > rear)
front = rear = -1;
printf("\n The number deleted is : %d", val);
}
}
void peek()
{
if(front==-1 || front>rear)
{
printf("\n QUEUE IS EMPTY");
}
else
{
printf("\n The first value in queue is : %d",queue[front]);
}
}
void display()
{
int i;
printf("\n");
if(front == -1 || front > rear)
printf("\n QUEUE IS EMPTY");
else
{
for(i = front;i <= rear;i++)
printf("\t %d", queue[i]);
}
}