-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.c
58 lines (58 loc) · 1.3 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
#include "queue.h"
#include "std.h"
#include "string.h"
#include <stdlib.h>
struct Queue {
void *elemArray;
size_t head, tail;
size_t maxNum;
size_t elemSize;
};
Queue createQueue(size_t elemSize, size_t elemMaxNum)
{
Queue queue = (Queue)malloc2(sizeof(struct Queue));
queue->elemArray = malloc2(elemSize * elemMaxNum);
queue->elemSize = elemSize;
queue->maxNum = elemMaxNum;
queue->head = queue->tail = 0;
return queue;
}
bool isFull(Queue queue)
{
if ((queue->tail + 1) % queue->maxNum == queue->head)
return true;
return false;
}
bool isEmpty(Queue queue)
{
if (queue->head == queue->tail)
return true;
return false;
}
void pop(Queue queue, void *elem)
{
memcpy(elem,
(char *)queue->elemArray + queue->elemSize * queue->head,
queue->elemSize);
queue->head = (queue->head + 1) % queue->maxNum;
}
void push(Queue queue, void *elem)
{
memcpy((char *)queue->elemArray + queue->elemSize * queue->tail,
elem,
queue->elemSize);
queue->tail = (queue->tail + 1) % queue->maxNum;
}
void freeQueue(Queue queue)
{
free2(queue->elemArray);
free2(queue);
}
void emptyQueue(Queue queue)
{
queue->head = queue->tail;
}
size_t getElemNum(Queue queue)
{
return abs(queue->tail - queue->head);
}