-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.c
154 lines (141 loc) · 2.74 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/**
*
* @file Queue.c
* @author Max Base ([email protected])
* @brief Queue data structure
* @version 0.1
* @date 2022-12-03
* @copyright Copyright (c) 2022
*
*/
#include "Queue.h"
// typedef struct node {
// int* data;
// int size;
// int count;
// int front;
// } Queue;
/**
* @brief Create a Queue object
* @return Queue*
*/
Queue* createQueue(int size)
{
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->data = (int*)malloc(sizeof(int) * size);
queue->size = size;
queue->count = 0;
queue->front = 0;
return queue;
}
/**
* @brief Destroy the Queue object
* @param queue
*/
void destroyQueue(Queue* queue)
{
free(queue->data);
free(queue);
}
/**
* @brief Check if the queue is empty
* @param queue
* @return true
* @return false
*/
bool isEmpty(Queue* queue)
{
return queue->count == 0;
}
/**
* @brief Check if the queue is full
* @param queue
* @return true
* @return false
*/
bool isFull(Queue* queue)
{
return queue->count >= queue->size;
}
/**
* @brief Enqueue an element to the queue
* @param queue
* @param element
*/
void enqueue(Queue* queue, int element)
{
if (isFull(queue)) {
printf("Queue is full!\n");
return;
}
queue->data[queue->count] = element;
queue->count++;
}
/**
* @brief Dequeue an element from the queue
* @param queue
* @return int
*/
int dequeue(Queue* queue)
{
if (isEmpty(queue)) {
printf("Queue is empty!\n");
return -1;
}
int element = queue->data[queue->front];
queue->front++;
return element;
}
/**
* @brief Get the Front object
* @param queue
* @return int
*/
int getFront(Queue* queue)
{
if (isEmpty(queue)) {
printf("Queue is empty!\n");
return -1;
}
return queue->data[queue->front];
}
/**
* @brief Print the queue
* @param queue
* @return char*
*/
char* printQueue(Queue* queue)
{
if (isEmpty(queue)) {
printf("Queue is empty!\n");
return NULL;
}
char* str = (char*)malloc(sizeof(char) * 100);
int rear = (queue->front + queue->count) % queue->size;
for (int i = queue->front; i < rear; i++) {
sprintf(str, "%s%d ", str, queue->data[i]);
}
return str;
}
/**
* @brief Get the Rear object
* @param queue
* @return int
*/
int getRear(Queue* queue)
{
if (isEmpty(queue)) {
printf("Queue is empty!\n");
return -1;
}
return queue->data[queue->count - 1];
}
/**
* @brief Get the Size object
* @param queue
* @return int
*/
int getSize(Queue* queue)
{
return queue->count - queue->front;
}