Circular Queue - Coder's point

Sunday, April 7, 2019

Circular Queue

 #include<stdio.h>  
 #include<conio.h>  
 #define MAX 10  
 void addq(int*,int,int*,int*);  
 int delq(int*,int*,int*);  
 void display(int*);  
 void main()  
 {  
 int arr[MAX];  
 int i,front,rear;  
 front=rear=-1;  
 for(i=0;i<MAX;i++)  
 arr[i]=0;  
 addq(arr,14,&front,&rear);  
 addq(arr,22,&front,&rear);  
 addq(arr,13,&front,&rear);  
 addq(arr,-6,&front,&rear);  
 addq(arr,25,&front,&rear);  
 printf("\nElement in circular queue:");  
 display(arr);  
 i=delq(arr,&front,&rear);  
 printf("\nitem deleted:%d",i);  
 i=delq(arr,&front,&rear);  
 printf("\nitem deleted:%d",i);  
 printf("\nElement in the circular queue after deletion:");  
 display(arr);  
 addq(arr,21,&front,&rear);  
 addq(arr,17,&front,&rear);  
 addq(arr,18,&front,&rear);  
 addq(arr,9,&front,&rear);  
 addq(arr,20,&front,&rear);  
 printf("\nElement in the circular queue after addition:");  
 display(arr);  
 addq(arr,12,&front,&rear);  
 printf("\nElement in the circular queue after addition:");  
 display(arr);  
 getch();  
 }  
 void addq(int *arr,int item,int *pfront,int *prear)  
 {  
 if((*prear==MAX-1 && *pfront==0)||(*prear+1==*pfront))  
 {  
 printf("\nQueue is full.");  
 }  
 if(*prear==MAX-1)  
 *prear=0;  
 else  
 (*prear)++;  
 arr[*prear]=item;  
 if(*pfront==-1)  
 *pfront=0;  
 }  
 int delq(int *arr,int *pfront,int *prear)  
 {  
 int data;  
 if(*pfront==-1)  
 {  
 printf("\nQueue is empty.");  
 return -1;  
 }  
 data=arr[*pfront];  
 arr[*pfront]=0;  
 if(*pfront==*prear)  
 {  
 *pfront=-1;  
 *prear=-1;  
 }  
 else  
 {  
 if(*pfront==MAX-1)  
 *pfront=0;  
 else (*pfront)++;  
 }  
 return data;  
 }  
 void display(int *arr)  
 {  
 int i;  
 printf("\n");  
 for(i=0;i<MAX;i++)  
 printf("%d\t",arr[i]);  
 printf("\n");  
 }  
OUTPUT:


Element in circular queue:
14        22        13        -6         25        0          0          0          0          0         
item deleted:14
item deleted:22
Element in the circular queue after deletion:
0          0          13        -6         25        0          0          0          0          0         
Element in the circular queue after addition:
0          0          13        -6         25        21        17        18        9          20       
Element in the circular queue after addition:
12        0          13        -6         25        21        17        18        9          20       

No comments:

Post a Comment