How to implement Queue and realize various operations to be performed on it.
In last post i talked about Stack so in this post i will talk about queue.
AIM:To Implement Queue and realize various operations to be performedon
Algorithm:
• Start
• Include all header files that are used in the program.
• Declaring all user-defined functions that are used to implement queues.
• Creating a one-dimensional array
• Defining two integer variables 'front' and 'rear'
• deciding for the operations to be executed using a case statement.
• defining all of the functions that will be used to carry out the operations
Enqueue :
- If rear = size (A) – 1
- Return Queue is full
- Else if Is Empty ()
- {
- front = rear =0
- A [rear] = x
- }
- Else
- {
- rear = rear +1
- A [rear] = x
- }
Dequeue :
- {
- if Is Empty()
- return
- else if front = rear
- front = rear = -1
- else
- front = front + 1
- }
Display:
- Define n
- If Front = -1 and Rear = -1
- print "Queue is Empty"
- Else
- for i = Front to Rear
- print queue[i]
- End for
Code:
#include <stdio.h>
#include <stdlib.h>
int size = 5;
int queue[5];
int front = -1, Rear = -1;
void isEmpty();
void Front();
void enqueue();
void dequeue();
void show();
void isEmpty() {
if(front == -1 && Rear == -1){
printf("\nEmpty Queue\n");
}
else{
printf("\nNot Empty\n");
}
}
void Front(){
printf("Element in Front is : %d\n",queue[0]);
}
void enqueue(){
int n;
if(Rear == size - 1 ){
printf("\nQueue overflow\n");
}
else{
if(front == -1 && Rear == -1){
printf("\nElement to be inserted in the Queue: ");
scanf("%d", &n);
front = front + 1;
Rear = Rear + 1;
queue[Rear] = n;
}
else{
printf("\nElement to be inserted in the Queue: ");
scanf("%d", &n);
Rear = Rear + 1;
queue[Rear] = n;
}
}
}
void dequeue(){
if(front == -1 && Rear == -1){
printf("\nQueue is Empty\n");
}
else{
printf("\nElement deleted from the queue : %d\n", queue[front]);
front = front + 1;
}
}
void display(){
if (front == - 1 && Rear == -1){
printf("\nEmpty Queue \n");
}
else
{
printf("\nElement in Queue : \n");
for (int i = front; i <= Rear; i++)
printf(" %d ", queue[i]);
}
printf("\n");
}
void main(){
int num;
printf("\n---20BCE2929---");
while(1) {
printf("\n1.isEmpty\n2.Front\n3.enqueue\n4.dequeue\n5.Display\n6.Exit");
printf("\nEnter your choice : ");
scanf("%d",&num);
if(num == 1){
isEmpty();
}
else if(num == 2){
Front();
}
else if(num == 3){
enqueue();
}
else if(num == 4){
dequeue();
}
else if(num == 5){
display();
}
else if(num == 6){
exit(0);
}
}
}
Posted with STEMGeeks