-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.c
74 lines (64 loc) · 1.29 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
#include "queue.h"
struct qnode *new_qnode(u32 k)
{
struct qnode *nq = malloc(sizeof(struct qnode));
nq->val = k;
nq->next = NULL;
return nq;
}
struct queue *new_queue()
{
struct queue *new_queue = malloc(sizeof(struct queue));
new_queue->front = new_queue->rear = NULL;
new_queue->ocupation=0;
return new_queue;
}
void enqueue(struct queue *q, u32 k)
{
struct qnode *nq = new_qnode(k);
q->ocupation+=1;
if (q->rear == NULL)
{
q->front = q->rear = nq;
return;
}
q->rear->next = nq;
q->rear = nq;
}
struct queue *dequeue(struct queue *q)
{
if(q->front == NULL)
return q;
struct qnode *prev_front = q->front;
q->front = q->front->next;
q->ocupation-=1;
if (q->front == NULL)
q->rear = NULL;
free(prev_front);
return q;
}
u32 front(struct queue *q)
{
return q->front->val;
}
bool queue_is_empty(struct queue *q)
{
return (q->front == NULL && q->rear == NULL);
}
void print_queue(struct queue *q)
{
struct qnode *t = q->front;
while(t != NULL)
{
printf("%d -> ", t->val);
t = t->next;
}
printf("[Ocupation: %d]\n",q->ocupation);
}
void destroy_queue(struct queue *q){
while (!queue_is_empty(q))
{
q = dequeue(q);
}
free(q);
}