-
Notifications
You must be signed in to change notification settings - Fork 2
/
queue.c
71 lines (61 loc) · 1.31 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
#include <stdlib.h>
#include <stdio.h>
int in_index, out_index;
int memory_size;
int queue_size = 0;
void **queue;
/*
* This method must be called before using a queue.
* size_ : the size of a queue
*/
void init_queue(int size_) {
/* Allocate memory and initialize indices */
queue_size = size_;
memory_size = queue_size+1;
queue = (void **)malloc(size_*sizeof(void *));
in_index = out_index = 0;
}
/*
* Returns the number of items in a queue.
*/
int get_n_items() {
return in_index-out_index;
}
int queue_is_empty() {
return get_n_items() == 0;
}
int queue_is_full() {
return get_n_items() == queue_size;
}
/*
* Enqueueing.
* item : a pointer to the item inserted to a queue
*/
void enqueue(void *item) {
if(queue_is_full()) {
printf("Fatal error: The queue is full.\n");
exit(-1);
}
queue[in_index] = item;
in_index = (in_index+1) % memory_size;
}
/*
* Dequeueing.
* Returns the address of the item
*/
void *dequeue() {
if(queue_is_empty()) {
printf("Fatal error: The queue is empty.\n");
exit(-1);
}
void *item;
item = queue[out_index];
out_index = (out_index+1) % memory_size;
return item;
}
/*
* This method must be called after using the queue to free the memory area.
*/
void free_queue() {
free(queue);
}