-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.c
71 lines (60 loc) · 1.39 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 <malloc.h>
#include <assert.h>
#include <stdbool.h>
#include "queue.h"
typedef void *pointer;
struct Queue {
unsigned long int front;
unsigned long int rear;
unsigned long int counter;
unsigned long int size;
pointer *queue;
};
/***Private functions***/
bool _isEmpty(Queue q) {
return (q->counter == 0);
}
unsigned long int _size(Queue q) {
return q->counter;
}
bool _isFull(Queue q) {
return (q->counter == q->size);
}
/***Public functions***/
void queueCreate(Queue *queue, unsigned long int size) {
assert(*queue == NULL);
int i = 0;
*queue = (Queue) malloc(sizeof(struct Queue));
(*queue)->counter = 0;
(*queue)->front = 0;
(*queue)->rear = 0;
(*queue)->size = size;
(*queue)->queue = malloc(sizeof(pointer) * size);
for (i = 0; i < (*queue)->size; i++) {
(*queue)->queue[i] = NULL;
}
}
bool enQueue(Queue q, pointer item) {
if (_isFull(q))
return false;
else {
q->counter++;
q->queue[q->rear] = item;
q->rear = (q->rear + 1) % q->size;
}
return true;
}
pointer deQueue(Queue q) {
pointer item = NULL;
if (!_isEmpty(q)) {
q->counter--;
item = q->queue[q->front];
q->front = (q->front + 1) % q->size;
}
return item;
}
void queueDestroy(Queue *queue) {
assert(*queue != NULL);
free((*queue)->queue);
free(*queue);
}