-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.h
108 lines (80 loc) · 2.54 KB
/
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define CAPACITY 5
typedef struct {
int* items;
size_t length;
size_t capacity;
} Queue;
void QueueInit(Queue** queue)
{
assert( (*queue) == NULL ); // assert if queue is already initialized
Queue* new_queue = malloc(sizeof(Queue));
new_queue->items = malloc(sizeof(int) * CAPACITY);
new_queue->length = 0;
new_queue->capacity = CAPACITY;
(*queue) = new_queue;
}
void Enqueue(Queue** queue, int item)
{
Queue* queue_copy = (*queue);
if (queue_copy == NULL) {
QueueInit(&queue_copy);
} else if (queue_copy->length >= queue_copy->capacity) {
// If we exceeded, reallocate
size_t new_capacity = queue_copy->capacity + 5;
queue_copy->items = realloc(queue_copy->items, new_capacity * sizeof(int));
queue_copy->capacity = new_capacity;
}
size_t next_item = queue_copy->length;
queue_copy->items[next_item] = item;
queue_copy->length++;
(*queue) = queue_copy;
}
void Dequeue(Queue** queue)
{
Queue* queue_copy = (*queue);
assert(queue_copy != NULL);
// Check if queue is empty
if (queue_copy->length == 0) return;
// FIXME: Maybe find a better way to alloc a new Queue in this case
Queue* new_queue = malloc(sizeof(Queue));
const size_t current_capacity = queue_copy->capacity;
new_queue->items = malloc(current_capacity * sizeof(int));
new_queue->capacity = current_capacity;
new_queue->length = 0;
// Copy elements from old queue to new, except for 0 index element
for (size_t i = 1; i < queue_copy->length; i++) {
Enqueue(&new_queue, queue_copy->items[i]);
}
new_queue->length = queue_copy->length - 1;
free(queue_copy);
(*queue) = new_queue;
}
void QueueClear(Queue** queue)
{
Queue* queue_copy = (*queue);
Queue* new_queue = NULL;
assert(queue_copy != NULL);
if (queue_copy->length == 0) return;
// Keep the same capacity, but allocate a new queue with length = 0
new_queue = malloc(sizeof(Queue));
const size_t current_capacity = queue_copy->capacity;
new_queue->items = malloc(sizeof(int) * current_capacity);
new_queue->capacity = current_capacity;
new_queue->length = 0;
free(queue_copy);
(*queue) = new_queue;
}
void QueuePrint(Queue* queue)
{
assert(queue != NULL);
if (queue->length == 0) {
printf("<queue empty>\n");
return;
}
for (size_t i = 0; i < queue->length; i++) {
printf("[%ld] = %i\n", i, queue->items[i]);
}
}