-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.c
94 lines (79 loc) · 1.52 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
85
86
87
88
89
90
91
92
93
94
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node * next;
} Node;
Node * newNode(int value) {
Node * n = (Node*)malloc(sizeof(Node));
n->value = value;
n->next = NULL;
return n;
}
typedef struct Queue {
Node * front;
Node * rear;
} Queue;
Queue * newQueue() {
Queue * q = (Queue*)malloc(sizeof(Queue));
q->front = NULL;
q->rear = NULL;
return q;
}
int isEmpty(Queue * q) {
return q->front == NULL;
}
void enqueue(Queue * q, int value) {
Node * no = newNode(value);
if(isEmpty(q)) {
q->front = no;
q->rear = no;
} else {
q->rear->next = no;
q->rear = no;
}
}
int dequeue(Queue * q) {
if(isEmpty(q))
exit(2);
Node * n = q->front;
int value = n->value;
if(q->front == q->rear) {
q->front = NULL;
q->rear = NULL;
} else {
q->front = q->front->next;
}
free(n);
return value;
}
int size(Queue * q) {
int size = 0;
Node * n = q->front;
while(n != NULL) {
size++;
n = n->next;
}
return size;
}
void printQueue(Queue * q) {
Node * n = q->front;
printf("[");
while(n != NULL) {
printf(" %d ", n->value);
n = n->next;
}
printf("] size: %d\n", size(q));
}
int main() {
Queue * q = newQueue();
for(int i=0; i<6; i++) {
enqueue(q, rand()%20);
printQueue(q);
}
for(int i=0; i<6; i++) {
printQueue(q);
dequeue(q);
}
return 0;
}