-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.c
More file actions
47 lines (39 loc) · 995 Bytes
/
queue.c
File metadata and controls
47 lines (39 loc) · 995 Bytes
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
#include "queue.h"
struct Queue *create_queue(size_t capacity){
if(capacity < 0){
perror("Can't use a negtivie value as capacity.");
return;
}
struct Queue *queue = malloc(
capacity * sizeof(struct Queue));
queue->capacity = capacity;
queue->size = 0;
queue->front = 0;
queue->rear = 0;
return queue;
}
void put_to_queue(struct Queue *queue, void *data){
if(queue->size >= queue->capacity ){
perror("The queue reached it capacity.");
return;
}
queue->data[queue->rear] = data;
queue->rear = (queue->rear + 1) % queue->capacity;
queue->size++;
}
void *pop_from_queue(struct Queue *queue){
if(queue->size == 0){
perror("The queue reached it capacity.");
return;
}
void *element = queue->data[queue->front];
queue->front = (queue->front + 1) % queue->capacity;
queue->size--;
return element;
}
void free_queue(struct Queue *queue){
for(int i = 0; i < queue->size; i++){
free(queue->data[i]);
}
free(queue);
}