forked from gzhang91/data_struct-study
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathqueue.c
More file actions
executable file
·77 lines (63 loc) · 1.39 KB
/
queue.c
File metadata and controls
executable file
·77 lines (63 loc) · 1.39 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
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "queue.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
Queue *QueueCreate(int size, int n) {
Queue *queue = (Queue *)malloc(sizeof(Queue));
if (!queue) {
printf("malloc failed!\n");
exit(-1);
}
queue->data = (char *)malloc(size * n);
if (!queue->data) {
printf("malloc failed!\n");
exit(-1);
}
queue->size = size;
queue->n = n;
queue->header = 0;
queue->tailer = 0;
}
void QueueRelease(Queue *queue) {
if (!queue) {
return;
}
if (queue->header == queue->tailer) {
return;
}
free(queue->data);
free(queue);
}
int QueueEn(Queue *queue, void *data) {
if (!queue) {
return 0;
}
if (QueueFull(queue)) {
printf("队列已满\n");
return 0;
}
memcpy(queue->data + queue->tailer * queue->size, (char *)data, queue->size);
queue->tailer ++;
queue->tailer = (queue->tailer) % queue->n;
return 1;
}
int QueueDe(Queue *queue, void *data) {
if (!queue) {
return 0;
}
if (QueueEmpty(queue)) {
printf("队列已空\n");
return 0;
}
char *target = (char *)data;
memcpy(target, queue->data + queue->header * queue->size, queue->size);
queue->header ++;
queue->header = (queue->header) % queue->n;
return 1;
}
int QueueEmpty(Queue *queue) {
return queue->header == queue->tailer;
}
int QueueFull(Queue *queue) {
return (queue->tailer + 1) % queue->n == queue->header;
}