A Queue can be defined as an ordered collection of items where items are added at one end and items are deleted at the other end. Hence the first item added in a Queue is the first item to be deleted .For this reason Queue is called fifo list. The end from which items are deleted in a Queue is called the front of the Queue and the other end is called the rear of the Queue.
Items can be inserted, at the rear end of the queue , items can be deleted from the front end of the queue. Item insertion has no limit as the rear end can grow but deletion of items from a queue is possible only when there is item in the queue.
Here is the program on queue
# include< stdio.h>
# include< string.h>
# define size 10
int rear, front;
int ch;
int x;
int q[size];
/* This array can work as a queue with maximum ten elements */
int rear = -1;
/* this variable will keep track of the elements inserted*/
int front = -1;
/*front will keep track of the elements deleted*/
void insert()
{
printf("\n Input the element :");
scanf("%d", &ch);
if(rear< size)
{
/* if block means insertion is possible.*/
rear ++;
q[rear] = ch ;
if(front == -1)
front = 0;
/* after inserting the first element, front becomes 0 .So we can delete elements. */
}
else
printf("\n Can't grow more.");
}
void del()
{
x=0;
if (front == -1)
{
printf("\n Underflow");
}
else
{
ch = q[front];
x=1;
printf("\n Element deleted : %d", ch);
}
if(front == rear)
{
/* front and rear will become same when all the inserted elements are deleted */
front =-1;
rear = -1;
}
else
front = front + 1;
/* after deleting an element front is incremented by 1 to access the next element.*/
}
void display()
{
int i;
if (front == -1)
return;
for(i = front ; i <= rear; i++)
printf(" %d ", q[i]);
}
void main()
{
int k = 0;
char choice;
clrscr();
do
{
printf("\nInsert->i Delete->d Quit->q:");
printf("\nInput the choice : ");
do
{
choice = getchar();
choice = tolower(choice);
}while(strchr("idq",choice)==NULL);
printf("Your choice is: %c ", choice);
switch(choice)
{
case 'i' :
{
insert();
printf("\nQueue after inserting ");
display();
break;
}
case 'd' :
{
del();
if(x==1)
{
printf("\nQueue content after deletion is as follows:\n");
display();
}
break;
}
case 'q':
{
k = 1;
}
}
} while(!k);
getch();
}
No comments:
Post a Comment