This repository was archived by the owner on Oct 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.c
More file actions
64 lines (52 loc) · 1.31 KB
/
queue.c
File metadata and controls
64 lines (52 loc) · 1.31 KB
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
#include <stdlib.h>
#include <stdio.h>
#include "queue.h"
queue* queate(int capacity){
queue* q = malloc(sizeof(queue));
if (q) {
q->first = 0;
q->size = 0;
q->capacity = capacity;
q->data = malloc(capacity * sizeof(int));
}
return q;
}
int enqueue(queue* q, int key){
if (!q) return 0;
if (q->size == q->capacity)
return 0;
int position = (q->first + q->size) % q->capacity;
q->data[position] = key;
q->size++;
return 1;
}
int* dequeue(queue* q){
if (q == NULL) return q;
else if (q->size > 0) {
int ex = q->first;
q->first = (q->first + 1) % q->capacity;
q->size--;
int* d = q->data[ex];
return d;
}
else return NULL;
}
void free_queue(queue* q){
if (q) {
// if q->data stores pointers of any kind, they should be freed too
free(q->data);
} free(q);
}
void printq(queue* q){
if (q != NULL) {
if (q->size > 0) {
int pos = q->first;
for (int i = 0; i < q->size - 1; i++) {
printf("%d ", q->data[pos]);
pos = (pos + 1) % q->capacity;
} printf("%d\n", q->data[pos]);
} else
printf("The queue is empty.\n");
}
else printf("There is no queue.\n");
}