-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueue.c
139 lines (82 loc) · 2.87 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "BinMaxHeap.h"
Queue* create_queue () {
Queue *queue;
if (!(queue = malloc (sizeof(Queue)))) {
fprintf(stderr,"Error allocating queue\n");
return NULL;
}
if (!(queue->array = malloc (INIT_QUEUE_SIZE * sizeof(qnode)))) {
fprintf(stderr,"Error allocating array in queue\n");
return NULL;
}
queue->first = -1;
queue->last = -1;
queue->size = INIT_QUEUE_SIZE;
queue->num = 0;
return queue;
}
void destroy_queue (Queue* queue) {
free (queue->array);
free (queue);
return ;
}
void queue_push (Queue* queue, qnode node) {
int size, first, next;
size = queue->size;
first = queue->first;
next = queue->last + 1;
if (next == queue->size) { //if last element of queue was in the last position of the array
//the "newly" added element should be added at the start of the array
next = 0; //(circle array format)
}
if (next == queue->first) { //if queue array is full (last + 1 == first), we need to realloc the
//queue's array
if (!(queue->array = realloc (queue->array, 2 * queue->size * sizeof(qnode)))) {
fprintf(stderr, "Error: reallocating queue array\n");
return ;
}
if (queue->array == NULL) {
fprintf(stderr,"Error re-allocating queue\n");
return ;
}
if (queue->last != queue->size - 1) { //when reallocing the queue's array , we fix the position of the elements
//inside the array (cause of circle format)
memmove (&(queue->array[size + first]), &(queue->array[first]), (size - first) * sizeof(qnode));
queue->first = size + first;
}
queue->size *= 2;
}
queue->last++;
if (queue->last == queue->size) {
queue->last = 0;
}
queue->array[queue->last] = node;
if (first == -1) {
queue->first = 0;
}
queue->num ++;
return ;
}
qnode queue_pop (Queue* queue) {
qnode retval = queue->array[queue->first];
if (queue->first == queue->last) {
queue->first = -1;
queue->last = -1;
}
else {
queue->first++;
if (queue->first == queue->size) {
queue->first = 0;
}
}
queue->num --;
return retval;
}
void empty_queue (Queue* queue) {
queue->first = -1;
queue->last = -1;
queue->num = 0;
}