-
Notifications
You must be signed in to change notification settings - Fork 1
/
queue.c
75 lines (61 loc) · 1.36 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
/*****************************************************************************
**
** queue.c
**
** Function implementations for Queue, a polymorphic FIFO data structure
**
** Author: Sean Butze
**
****************************************************************************/
#include <assert.h>
#include <stdlib.h>
#include "queue.h"
Queue* Queue_new() {
Queue *q = malloc(sizeof(Queue));
q->size = 0;
q->head = NULL;
q->tail = NULL;
return q;
}
void Queue_add(Queue *q, void *el) {
Node *temp = q->head;
Node *new_tail = malloc(sizeof(Node));
new_tail->val = el;
new_tail->next = NULL;
if (q->size < 1) {
q->head = new_tail;
} else {
q->tail->next = new_tail;
}
q->tail = new_tail;
q->size++;
}
void* Queue_front(Queue *q) {
assert(q && q->size > 0);
return (q->head->val);
}
void* Queue_remove(Queue *q) {
assert(q && q->size > 0);
Node *head = q->head;
void *headval = head->val;
q->head = head->next;
if (q->size == 1) {
q->tail = NULL; // Prevent dangling pointer
}
q->size--;
free(head);
return (headval);
}
unsigned Queue_size(Queue *q) {
assert(q);
return(q->size);
}
void Queue_delete(Queue *q) {
assert(q);
Node *i1, *i2;
for (i1 = q->head; i1; i1 = i2) {
i2 = i1->next;
free(i1);
}
free(q);
}