-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircular_queue.c
More file actions
68 lines (56 loc) · 1.16 KB
/
Copy pathcircular_queue.c
File metadata and controls
68 lines (56 loc) · 1.16 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
#include <stdio.h>
#define CAPACITY 5
typedef struct {
int data[CAPACITY];
int front, rear, count;
} Queue;
void init(Queue *q) {
q->front = 0;
q->rear = -1;
q->count = 0;
}
int isEmpty(Queue *q) {
return q->count == 0;
}
int isFull(Queue *q) {
return q->count == CAPACITY;
}
/* --- enqueue --- */
void enqueue(Queue *q, int value) {
if(isFull(q)){
printf("Full! Could not add %d\n", value);
return;
}
q->rear = (q->rear+1) % CAPACITY ;
q->data[q->rear] = value;
q->count++;
printf("Added : %d (rear= %d) (count= %d)\n", value,q->rear, q->count);
return;
}
/* --- dequeue --- */
int dequeue(Queue *q) {
if(isEmpty(q)){
printf("Empty ! ");
return -1;
}
int result = q->data[q->front];
q->front = (q->front+1) % CAPACITY;
q->count--;
return result;
// hint: front = (front + 1) % CAPACITY;
}
int main(void) {
Queue q;
init(&q);
enqueue(&q, 10);
enqueue(&q, 20);
enqueue(&q, 30);
enqueue(&q, 40);
enqueue(&q, 50);
dequeue(&q);
dequeue(&q);
enqueue(&q, 60);
enqueue(&q, 70);
enqueue(&q, 80);
return 0;
}