-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.c
84 lines (68 loc) · 1.4 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
#include "queue.h"
queue_t *create_queue()
{
queue_t *queue;
queue = (queue_t *) malloc (sizeof(queue_t));
queue->first = NULL;
queue->last = NULL;
queue->size = 0;
return queue;
}
void enqueue(queue_t *queue, int value)
{
queue_node_t *entry;
entry = (queue_node_t *) malloc (sizeof(queue_node_t));
entry->value = value;
entry->next = NULL;
if(queue->last != NULL)
queue->last->next = entry;
queue->last = entry;
if(queue->first == NULL)
queue->first = queue->last;
queue->size++;
}
int dequeue(queue_t *queue)
{
int value;
queue_node_t *tmp;
if(queue->size > 0)
{
value = queue->first->value;
tmp = queue->first->next;
free(queue->first);
queue->first = tmp;
queue->size--;
if(queue->size == 0)
{
queue->last = NULL;
queue->first = NULL;
}
return value;
}
else
exit(1);
}
void clear_queue(queue_t *queue)
{
while(queue->size)
{
dequeue(queue);
}
free(queue);
}
void test_queue()
{
queue_t *q;
q = create_queue();
enqueue(q,13);
enqueue(q,7);
enqueue(q,666);
printf("%d\n",dequeue(q));
printf("%d\n",dequeue(q));
enqueue(q,42);
printf("%d\n",dequeue(q));
printf("%d\n",dequeue(q));
enqueue(q,55);
printf("%d\n",dequeue(q));
clear_queue(q);
}