-
Notifications
You must be signed in to change notification settings - Fork 0
/
queueChar.c
55 lines (54 loc) · 1.13 KB
/
queueChar.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
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
struct queue{
char **v;
int head;
int tail;
int size;
int maxsize;
};
struct queue *queue_create(int maxsize)
{
struct queue *q = malloc(sizeof(*q));
q->v = (char**)malloc(sizeof(char*) * maxsize);
if (q != NULL){
int i;
for(i = 0; i < maxsize + 1; i++){
q->v[i] = (char*)malloc(sizeof(char)*500);
}
if (q->v == NULL){
free(q); return NULL;
}
q->maxsize = maxsize;
q->size = 0;
q->head = maxsize + 1;
q->tail = 0;
}
return q;
}
void queue_free(struct queue *q){
free(q->v);
free(q);
}
int queue_size(struct queue *q)
{
return q->size;
}
int queue_enqueue(struct queue *q, char* value){
if (q->head == q->tail + 1)
return -1;
q->v[q->tail++] = value;
q->tail = q->tail % (q->maxsize + 1);
q->size++;
return 0;
}
char* queue_dequeue(struct queue *q){
if (q->head % (q->maxsize + 1) == q->tail){
return "queue is empty";
}
q->head = q->head % (q->maxsize + 1);
q->size--;
return q->v[q->head++];
}