-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.c
128 lines (104 loc) · 1.75 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include "queue.h"
#include "debug.h"
#include <stdio.h>
#include <stdlib.h>
queue_hdl_t *
queue_create() {
queue_hdl_t *hdl;
hdl = (queue_hdl_t *)malloc(sizeof(queue_hdl_t));
if(hdl == NULL) {
#ifdef DEBUG
info("malloc failed");
#endif
return NULL;
}
hdl->first = NULL;
hdl->last = NULL;
hdl->size = 0;
return hdl;
}
void
queue_destroy(queue_hdl_t *hdl) {
free(hdl);
hdl = NULL;
}
void
queue_enqueue(queue_hdl_t *hdl, void *data) {
queue_node_t *newnode;
if(hdl == NULL) {
#ifdef DEBUG
info("Invalid handle");
#endif
return;
}
newnode = (queue_node_t *)malloc(sizeof(queue_node_t));
if(newnode == NULL) {
#ifdef DEBUG
info("malloc failed");
#endif
return;
}
hdl->size++;
newnode->data = data;
newnode->next = NULL;
/* First node */
if(hdl->last == NULL) {
hdl->last = newnode;
hdl->first = newnode;
return;
}
hdl->last->next = newnode;
hdl->last = newnode;
return;
}
void *
queue_dequeue(queue_hdl_t *hdl) {
queue_node_t *qnodep;
void *data;
if(hdl == NULL) {
#ifdef DEBUG
info("Invalid handle");
#endif
return NULL;
}
qnodep = hdl->first;
/* No nodes */
if(qnodep == NULL) {
return NULL;
}
if(qnodep == hdl->last) {
hdl->last = NULL;
}
hdl->first = qnodep->next;
hdl->size--;
data = qnodep->data;
free(qnodep);
qnodep = NULL;
return data;
}
int
queue_size(queue_hdl_t *hdl) {
return hdl->size;
}
/*
* Redefine struct tst_data as needed
*/
void
queue_printstring(queue_hdl_t *hdl) {
queue_node_t *s;
#ifdef TESTQUEUE
struct tst_data {
char *tst_data;
int tst_datalen;
} *q_data;
#endif
s = hdl->first;
while(s != NULL) {
#ifdef TESTQUEUE
q_data = (struct tst_data *)s->data;
printf("%s(%d) => ", q_data->tst_data, q_data->tst_datalen);
#endif
s = s->next;
}
printf("\n");
}