-
Notifications
You must be signed in to change notification settings - Fork 0
/
circular_queue.h
84 lines (69 loc) · 1.55 KB
/
circular_queue.h
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
#ifndef CIRCULAR_QUEUE
#define CIRCULAR_QUEUE
// Definitions
struct circular_queue
{
int front;
int rear;
int size;
int *arr;
};
void init_queue(struct circular_queue *queue, int size);
void free_queue(struct circular_queue *queue);
int isFull(struct circular_queue *queue);
void enqueue(struct circular_queue *queue, int value);
int dequeue(struct circular_queue *queue);
// Implementation
void init_queue(struct circular_queue *queue, int size)
{
queue->front = -1;
queue->rear = -1;
queue->size = size;
queue->arr = malloc(sizeof(int) * size);
}
void free_queue(struct circular_queue *queue)
{
free(queue->arr);
}
int isFull(struct circular_queue *queue)
{
if ((queue->front == 0 && queue->rear == queue->size - 1) ||
(queue->rear == (queue->front-1)%(queue->size - 1)))
{
return 1;
}
return 0;
}
void enqueue(struct circular_queue *queue, int value)
{
if (queue->front == -1)
{
queue->front = queue->rear = 0;
queue->arr[queue->rear] = value;
}
else if (queue->rear == queue->size - 1 && queue->front != 0)
{
queue->rear = 0;
queue->arr[queue->rear] = value;
}
else
{
queue->rear++;
queue->arr[queue->rear] = value;
}
}
int dequeue(struct circular_queue *queue)
{
int element = queue->arr[queue->front];
if (queue->front == queue->rear)
{
queue->front = -1;
queue->rear = -1;
}
else
{
queue->front = (queue->front + 1) % queue->size;
}
return element;
}
#endif