-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathqueue.c
55 lines (42 loc) · 967 Bytes
/
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
#include "queue.h"
#include <stdio.h>
queue_t *queue_init(void) {
queue_t* queue = (queue_t*)malloc(sizeof(queue_t));
queue->head = NULL;
queue->tail = NULL;
queue->n = 0;
return queue;
}
void enqueue(queue_t* queue, void *data) {
node_t* node = (node_t *)malloc(sizeof(node_t));
node->next = NULL;
node->data = data;
if (queue->tail != NULL) {
queue->tail->next = node;
}
queue->tail = node;
if (queue->head == NULL) {
queue->head = queue->tail;
}
queue->n += 1;
}
void *dequeue(queue_t* queue) {
node_t* node;
if (queue->n == 0)
return NULL;
node = queue->head;
queue->head = queue->head->next;
node->next = NULL;
if (queue->head == NULL) {
queue->tail = NULL;
}
void* data = node->data;
free(node);
queue->n -= 1;
return data;
}
void free_queue(queue_t* queue) {
while (queue->n != 0)
dequeue(queue);
free(queue);
}