Queue Operations
Algorithm
Enqueue(queue, n, front, rear, item)//inserts item into a queue 1. [queue already filled?] If front := 1 and rear := n or front := rear +1 then: Print OVERFLOW and return 2. [find new value of rear] If front : =NULL , then [Q initially empty] Set front := 1 and rear := 1; Else if rear := n then set rear := 1; Else set rear : = rear + 1; 3. Set queue[rear] := item [inserts new element]. 4. Return; Dequeue(queue, n, front, rear, item) //deletes element from q and assign it to variable item. 1. [Queue already empty?] If front := NULL then : print UNDERFLOW and return. 2. Set item : = queue[front]. 3. [find new value of front] If front=rear then, [queue has only one element] Set front=rear=NULL; Else if front=n then : set front := 1; Else set front : = front +1; 4. Return.
Algorithm Description
C Code
#include<stdio.h>
#include<conio.h>
int arr[50],n;
int rear=-1;
int front=-1,flag=0;
void isfull()
{
if (rear==n-1)
{
printf("Queue Overflow\n");
flag=1;
}
}
void isempty()
{
if (front == -1||front>rear)
{
printf("Queue Underflow\n");
flag=1;
}
}
void insert()
{
int added_item;
isfull();
if(flag==0)
{
if (front==-1)
front=0;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
rear=rear+1;
arr[rear] = added_item ;
}
}
void del()
{
isempty();
if(flag==0)
{
printf("Element deleted from queue is : %d\n",arr[front]);
front=front+1;
}
}
void display()
{
int i;
if (front==-1)
printf("Queue is empty\n");
else
{
printf("Queue is :\n");
for(i=front;i<= rear;i++)
printf("%d\t ",arr[i]);
}
}
void size()
{
int s= rear-front+1;
printf("\n size of queue is %d ",s);
}
void fron()
{
printf("front element is %d ",arr[front]);
}
int main()
{
int choice;
printf("length of queue is ");
scanf("%d",&n);
while(1)
{
printf("\n\n1.Insert\n");
printf("2.Delete\n");
printf("3.Display\n");
printf("4.Front element\n");
printf("5.Size\n");
printf("6: queue is full\n");
printf("7: queue is empty\n");
printf("8.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :insert();
break;
case 2 :del();
break;
case 3:display();
break;
case 4:fron();
break;
case 5:size();
break;
case 6:isfull();
break;
case 7:isempty();
break;
case 8:exit(1);
default:
printf("Wrong choice\n");
}
}
return 0;
}