-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircbuf.c
More file actions
103 lines (95 loc) · 1.71 KB
/
circbuf.c
File metadata and controls
103 lines (95 loc) · 1.71 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum Operations {
ENQ, DEQ, EMPTY
};
int mapping(char *s)
{
if (strcmp(s, "ENQ") == 0)
return 0;
if (strcmp(s, "DEQ") == 0)
return 1;
if (strcmp(s, "EMPTY") == 0)
return 2;
return -1;
}
struct Queue {
int *data;
int cap, count, head, tail;
};
struct Queue InitQueue()
{
struct Queue q;
q.data = (int*)malloc(4 * sizeof(int));
q.cap = 4;
q.count = q.head = q.tail = 0;
return q;
}
int QueueEmpty(struct Queue *q)
{
return (q->count == 0);
}
void Enqueue(struct Queue *q, int x)
{
if (q->count == q->cap) {
int *helper = (int*)malloc(2 * q->cap * sizeof(int));
int helperIndex = 0, i;
for (i = q->head; i < q->cap; i++) {
helper[helperIndex] = q->data[i];
helperIndex++;
}
for (i = 0; i < q->tail; i++) {
helper[helperIndex] = q->data[i];
helperIndex++;
}
free(q->data);
q->data = helper;
q->cap = q->cap * 2;
q-> head = 0;
q-> tail = helperIndex;
}
q->data[q->tail] = x;
q->tail = q->tail + 1;
if (q->tail == q->cap)
q->tail = 0;
q->count = q->count + 1;
return;
}
int Dequeue(struct Queue *q)
{
int x = q->data[q->head];
q->head = q->head + 1;
if (q->head == q->cap)
q->head = 0;
q->count = q->count - 1;
return x;
}
int main(int argc, char **argv)
{
char operation[6];
struct Queue q;
q = InitQueue();
int x, i, head;
do {
scanf("%s", operation);
switch (mapping(operation)) {
case ENQ:
scanf("%d\n", &x);
Enqueue(&q, x);
break;
case DEQ:
head = Dequeue(&q);
printf("%d\n", head);
break;
case EMPTY:
if (! QueueEmpty(&q))
printf("false\n");
else
printf("true\n");
break;
}
} while (strcmp(operation, "END") != 0);
free(q.data);
return 0;
}