-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.c
86 lines (80 loc) · 2.01 KB
/
queue.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
79
80
81
82
83
84
85
86
#include <stdio.h>
#include <stdlib.h>
/* Queue class, of size capacity,
* front is where we dequeue,
* with count elements currently in queue,
* stored in array[] in a circular fashion.
* Why do we not store front and back?
* Because they could both take size values,
* but queue has size*size non-empty and one empty states,
* so we would need an additional flag
* to tell if front==back is empty or full. */
struct queue {
int size;
int front;
int count;
int *array;
};
// Init queue: allocate array, set queue to empty.
void queueInit(struct queue * q, int n) {
q->size = n;
q->front = 0;
q->count = 0;
q->array = malloc(n*sizeof(int));
}
// Enqueue an element at back = front + count (mod size).
void enqueue(struct queue * q, int element) {
if (q->count == q->size) {
fprintf(stderr, "Error: queue overflow.\n");
exit(-1);
}
q->array[(q->front + q->count) % q->size] = element;
q->count++;
}
// Dequeue an element at front.
int dequeue(struct queue * q) {
if (q->count == 0) {
fprintf(stderr, "Error: queue underflow.\n");
exit(-1);
}
int element = q->array[q->front];
q->front = (q->front+1) % q->size;
q->count--;
return element;
}
// Free space when done.
void queueFree(struct queue * q) {
free(q->array);
}
int main() {
// The queue instance.
struct queue q;
// Initialize to size 4.
queueInit(&q, 4);
// Start enqueueing and dequeueing.
// This is the place to test for under and overflow.
enqueue(&q, 1);
printf("%d\n", dequeue(&q));
enqueue(&q, 2);
printf("%d\n", dequeue(&q));
enqueue(&q, 3);
enqueue(&q, 4);
enqueue(&q, 5);
printf("%d\n", dequeue(&q));
printf("%d\n", dequeue(&q));
printf("%d\n", dequeue(&q));
enqueue(&q, 5);
enqueue(&q, 6);
enqueue(&q, 7);
printf("%d\n", dequeue(&q));
enqueue(&q, 8);
printf("%d\n", dequeue(&q));
printf("%d\n", dequeue(&q));
enqueue(&q, 9);
printf("%d\n", dequeue(&q));
printf("%d\n", dequeue(&q));
// Free queue memory in the end.
queueFree(&q);
// Return success.
return 0;
}