-
Notifications
You must be signed in to change notification settings - Fork 0
/
circbuf.c
78 lines (72 loc) · 1.5 KB
/
circbuf.c
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Queue_s
{
int *buffer;
int head;
int tail;
int len, buf_size;
} Queue;
void InitQueue(Queue *q)
{
q->buf_size = 4;
q->len = 0;
q->buffer = (int *) malloc(q->buf_size * sizeof(int));
q->head = q->tail = 0;
}
void Resize(Queue *q)
{
int *new_buffer = (int *) malloc(q->buf_size * 2 * sizeof(int));
int i = q->head, i_new = 0;
do
{
new_buffer[i_new] = q->buffer[i];
i_new++;
i = (i + 1) % q->buf_size;
} while (i != q->tail);
q->head = 0;
q->tail = q->buf_size;
q->buf_size *= 2;
free(q->buffer);
q->buffer = new_buffer;
}
void Enqueue(Queue *q, int x)
{
q->len++;
if (q->len > q->buf_size)
Resize(q);
q->buffer[q->tail] = x;
q->tail = (q->tail + 1) % q->buf_size;
}
int Dequeue(Queue *q)
{
q->len--;
int result = q->buffer[q->head];
q->head = (q->head + 1) % q->buf_size;
return (result);
}
int main()
{
int n;
Queue q;
InitQueue(&q);
scanf("%d", &n);
char command[10];
for (int i = 0; i < n; i++)
{
scanf("%s", command);
if (strcmp(command, "ENQ") == 0)
{
int x;
scanf("%d", &x);
Enqueue(&q, x);
}
else if (strcmp(command, "DEQ") == 0)
printf("%d\n", Dequeue(&q));
else
printf("%s\n", (q.len == 0) ? "true" : "false");
}
free(q.buffer);
return (0);
}