forked from justin-lathrop/c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.c
125 lines (99 loc) · 2.06 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
/*
* @author: jelathro
* @date: 10/27/13
*
* Queue implementation file.
*/
#include <stdio.h>
#include <stdlib.h>
#include "Queue.h"
Queue_t queue_initialize(){
Queue_t q = { 0, 0 };
return(q);
}
int queue_push(Queue_t * q, void * d){
QueueItem_t * tmp;
if(q->size == 0){
q->head = (QueueItem_t *) malloc( sizeof(QueueItem_t) );
if (q->head == NULL) {
printf("\nERROR: Insufficient memory. Terminating...");
exit(EXIT_FAILURE);
}
q->head->next = 0;
q->head->data = d;
}else{
tmp = q->head;
q->head = (QueueItem_t *) malloc( sizeof(QueueItem_t) );
if (q->head == NULL) {
printf("\nERROR: Insufficient memory. Terminating...");
exit(EXIT_FAILURE);
}
q->head->data = d;
q->head->next = tmp;
}
q->size++;
return(1);
}
int queue_pop(Queue_t * q, queue_callback_func_pop cb){
// Temporary "iterator" on the list
QueueItem_t * nextItem = q->head;
if(q->size == 0) return(0);
if(q->size == 1){
if( cb(q->head->data) ){
free(q->head);
q->size--;
return(1);
}else{
return(0);
}
}
// Move to one before end of list
while(nextItem->next){
if(!nextItem->next->next){
// Remove last list item
if( cb(nextItem->next->data) ){
free(nextItem->next);
}else{
return(0);
}
nextItem->next = 0;
q->size--;
return(1);
}else{
nextItem = nextItem->next;
}
}
return(0);
}
void * queue_front(Queue_t * q){
QueueItem_t * tmp = q->head;
if(q->size == 0) return( (void *)0);
while(tmp->next){
tmp = tmp->next;
}
return( tmp->data );
}
void queue_for_each(Queue_t * q, queue_callback_func cb){
QueueItem_t * next = q->head;
int idx = 0;
if(q->size == 0) return;
while(next){
cb(idx, next->data);
idx++;
next = next->next;
}
}
int queue_remove(Queue_t * q, queue_callback_func_pop cb){
QueueItem_t * tmp;
QueueItem_t * next = q->head;
while(next){
tmp = next;
next = next->next;
if(cb(tmp->data)){
free(tmp);
}else{
return(0);
}
}
return(1);
}