-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.c
80 lines (69 loc) · 1.15 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
#include <assert.h>
#include <stdlib.h>
#include "queue.h"
void queue_init(queue* q)
{
q->head = NULL;
q->tail = NULL;
q->free_head = NULL;
}
void queue_push_back(queue* q, packed_node *node)
{
queue_element* new_element;
if(q->free_head != NULL)
{
new_element = q->free_head;
q->free_head = new_element->next;
}
else
{
new_element = malloc(sizeof(*new_element));
}
new_element->node = node;
new_element->next = NULL;
if(q->head == NULL)
{
q->head = new_element;
q->tail = new_element;
}
else
{
q->tail->next = new_element;
q->tail = new_element;
}
}
int queue_has_elements(queue* q)
{
return (q->head != NULL);
}
packed_node *queue_pop(queue* q)
{
assert(queue_has_elements(q));
queue_element* t_element;
t_element = q->head;
q->head = t_element->next;
if(q->head == NULL)
{
q->tail = NULL;
}
t_element->next = q->free_head;
q->free_head = t_element;
return t_element->node;
}
void queue_destory(queue* q)
{
queue_element* t = q->head;
while(t != NULL)
{
queue_element *next = t->next;
free(t);
t = next;
}
t = q->free_head;
while(t != NULL)
{
queue_element *next = t->next;
free(t);
t = next;
}
}