-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueue.c
More file actions
122 lines (104 loc) · 2.55 KB
/
CircularQueue.c
File metadata and controls
122 lines (104 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
//10 b)
#include <stdio.h>
#include <stdlib.h>
typedef struct Cirq{
int front;
int rear;
int*q;
int capacity;
}Cirq;
void enqueue(Cirq*p){
if(p->front==((p->rear)+1)%p->capacity){
printf("Resizing Circular Queue...\n");
int*newarr=(int*)realloc(p->q,p->capacity*2*sizeof(int));
if(newarr==NULL){
printf("Memory allocation failed...\n");
return;
}
p->q=newarr;
if(p->front>p->rear){
for(int i=0;i<=p->rear;i++){
p->q[p->capacity+i]=p->q[i];
}
p->rear+=p->capacity;
}
p->capacity*=2;
}
int val;
printf("Enter the value to enqueue: ");
scanf("%d",&val);
if(p->front==-1){
p->front=0;
}
p->rear=(p->rear+1)%p->capacity;
p->q[p->rear]=val;
}
void display(Cirq*p){
if(p->front==-1){
printf("Circular Queue is Empty\n");
return;
}
printf("\nCircular Queue:\t");
for(int i=p->front;i!=p->rear;i=(i+1)%p->capacity){
printf("%d ",p->q[i]);
}
printf("%d\n",p->q[p->rear]);
}
void dequeue(Cirq*p){
if(p->front==-1){
printf("Circualr Queue Underflow\n");
return;
}
printf("Dequeueud value: %d\n",p->q[p->front]);
if(p->front==p->rear){
p->front=p->rear=-1;
}
else{
p->front=(p->front+1)%p->capacity;
}
}
void peek(Cirq*p){
if(p->front==-1){
printf("Queue Empty\n");
return;
}
printf("First element of Circular Queue: %d\n",p->q[p->front]);
}
void main(){
int ch;
Cirq*p=(Cirq*)malloc(sizeof(Cirq));
if(p==NULL){
printf("Memory allocation failed...\n");
return;
}
p->front=p->rear=-1;
printf("Enter maximum capacity of the circular queue: ");
scanf("%d",&p->capacity);
p->q=(int*)calloc(p->capacity,sizeof(int));
for(;;){
printf("\nENTER:\n1. To enqueue\n2. To display\n3. To dequeue\n4. To peek\n0. To EXIT\n");
printf("Enter your choice from above: ");
scanf("%d",&ch);
switch(ch){
case 1:
enqueue(p);
break;
case 2:
display(p);
break;
case 3:
dequeue(p);
break;
case 4:
peek(p);
break;
case 0:
printf("Exiting...\n");
free(p);
free(p->q);
exit(0);
default:
printf("Invalid Choice! Please Enter Again!\n");
}
}
}