-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrdinaryQueue.c
More file actions
113 lines (95 loc) · 2.31 KB
/
OrdinaryQueue.c
File metadata and controls
113 lines (95 loc) · 2.31 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
//10 a)
#include <stdio.h>
#include <stdlib.h>
typedef struct Queue{
int capacity;
int*q;
int front;
int rear;
}Queue;
void display(Queue*p){
if(p->front==-1){
printf("Queue Empty\n");
return;
}
printf("\nQUEUE:\t");
for(int i=p->front;i<=p->rear;i++){
printf("%d ",p->q[i]);
}
printf("\n");
}
void enqueue(Queue*p){
if(p->rear==p->capacity-1){
printf("Reallocating size...\n");
int*newarr=(int*)realloc(p->q,p->capacity*2*(sizeof(int)));
if(newarr==NULL){
printf("Memory allocation failed...\n");
return;
}
p->q=newarr;
p->capacity*=2;
}
int val;
printf("Enter the value to enqueue: ");
scanf("%d",&val);
if(p->front==-1){
p->front=0;
}
p->q[++p->rear]=val;
}
void dequeue(Queue*p){
if(p->front==-1){
printf("Queue Underflow\n");
return;
}
printf("Dequeued value: %d\n",p->q[p->front]);
for(int i=p->front;i<p->rear;i++){
p->q[i]=p->q[i+1];
}
p->rear--;
if(p->front>p->rear){
p->front=p->rear=-1;
}
}
void peek(Queue*p){
if(p->front==-1){
printf("Queue Underflow\n");
return;
}
printf("First Element In Queue-> %d\n",p->q[p->front]);
}
void main(){
int ch;
Queue*p=(Queue*)malloc(sizeof(Queue));
if(p==NULL){
printf("Memory allocation failed...\n");
return;
}
p->front=p->rear=-1;
printf("Enter the maximum capacity of the 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\nEnter 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");
exit(0);
default:
printf("Invalid Choice! Please Enter Again!\n");
}
}
}