-
Notifications
You must be signed in to change notification settings - Fork 0
/
token_queue.c
59 lines (51 loc) · 1.26 KB
/
token_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
#include "token_queue.h"
#include <stdlib.h>
static void enqueue(TokenQueue* self, char* token);
static Token* dequeue(TokenQueue* self);
static bool is_empty(TokenQueue* self);
static void delete(TokenQueue* self);
TokenQueue* new_token_queue()
{
TokenQueue* self = malloc(sizeof (TokenQueue));
self->head = self->tail = NULL;
self->enqueue = &enqueue;
self->dequeue = &dequeue;
self->isEmpty = &is_empty;
self->delete = &delete;
return self;
}
TokenNode* new_token_node(char* token);
void enqueue(TokenQueue* self, char* token)
{
TokenNode* node = new_token_node(token);
if (is_empty(self)) {
self->head = self->tail = node;
} else {
self->tail = self->tail->next = node;
}
}
Token* dequeue(TokenQueue* self)
{
TokenNode* dequeued = self->head;
if (!dequeued) return NULL;
self->head = self->head->next;
if (dequeued == self->tail) {
self->tail = NULL;
}
Token* token = dequeued->token;
dequeued->delete(dequeued);
return token;
}
bool is_empty(TokenQueue* self)
{
return !self->head;
}
void delete(TokenQueue* self)
{
TokenNode* next;
for (TokenNode* node = self->head; node; node = next) {
next = node->next;
node->delete(node);
}
free(self);
}