-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.c
63 lines (52 loc) · 1.5 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
/* Implementation of a simple circular queue using a static array */
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
/* create the queue data structure and initialize it */
queue *queue_init(int n) {
queue *q = (queue *)malloc(sizeof(queue));
q->size = n;
q->buffer = malloc(sizeof(int)*n);
q->start = 0;
q->end = 0;
q->count = 0;
return q;
}
/* insert an item into the queue, update the pointers and count, and
return the no. of items in the queue (-1 if queue is null or full) */
int queue_insert(queue *q, int item) {
if ((q == NULL) || (q->count == q->size))
return -1;
q->buffer[q->end % q->size] = item;
q->end = (q->end + 1) % q->size;
q->count++;
return q->count;
}
/* delete an item from the queue, update the pointers and count, and
return the item deleted (-1 if queue is null or empty) */
int queue_delete(queue *q) {
if ((q == NULL) || (q->count == 0))
return -1;
int x = q->buffer[q->start];
q->start = (q->start + 1) % q->size;
q->count--;
return x;
}
/* display the contents of the queue data structure */
void queue_display(queue *q) {
int i;
if (q != NULL && q->count != 0) {
printf("queue has %d elements, start = %d, end = %d\n",
q->count, q->start, q->end);
printf("queue contents: ");
for (i = 0; i < q->count; i++)
printf("%d ", q->buffer[(q->start + i) % q->size]);
printf("\n");
} else
printf("queue empty, nothing to display\n");
}
/* delete the queue data structure */
void queue_destroy(queue *q) {
free(q->buffer);
free(q);
}