-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQUEUE.c
128 lines (99 loc) · 2.48 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 <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#define STR_SIZE 24
typedef struct {
union {
int32_t i32;
float f32;
char str[STR_SIZE];
} data;
void (*print)(void*);
void* next;
} NODE;
typedef struct {
NODE* front;
NODE* back;
} QUEUE;
void i32(void* i32);
void f32(void* f32);
void str(void* str);
void print(QUEUE* queue);
NODE* create_node(void* data, void (*type)(void*));
void enqueue(QUEUE* queue, void* data, void (*type)(void*));
void dequeue(QUEUE* queue);
void destroy(QUEUE* queue);
int32_t main() {
QUEUE queue = {NULL, NULL};
float f32_num = 3.14;
for (int32_t num = 0; num <= 5; ++num) {
enqueue(&queue, &num, i32);
}
dequeue(&queue);
enqueue(&queue, "Hello", str);
enqueue(&queue, &f32_num, f32);
print(&queue);
destroy(&queue);
return 0;
}
void i32(void* i32) {
printf("%d ", *((int32_t*)i32));
}
void f32(void* f32) {
printf("%.2f ", *((float*)f32));
}
void str(void* str) {
printf("%s ", (char*)str);
}
void print(QUEUE* queue) {
NODE* curr = queue->front;
while(curr != NULL) {
curr->print(&curr->data);
curr = curr->next;
}
}
NODE* create_node(void* data, void (*type)(void*)) {
NODE* new_node = malloc(sizeof(NODE));
if(new_node == NULL) {
return NULL;
}
new_node->print = type;
new_node->next = NULL;
if (type == i32) {
new_node->data.i32 = *((int32_t*)data);
} else if (type == f32) {
new_node->data.f32 = *((float*)data);
} else if (type == str) {
strncpy(new_node->data.str, (char*)data, STR_SIZE - 1);
new_node->data.str[STR_SIZE - 1] = '\0'; // Ensure null termination
}
return new_node;
}
void enqueue(QUEUE* queue, void* data, void (*type)(void*)) {
NODE* new_node = create_node(data, type);
if (new_node == NULL) {
return;
}
if (queue->front == NULL) {
queue->front = queue->back = new_node;
return;
}
queue->back->next = new_node;
queue->back = new_node;
}
void dequeue(QUEUE* queue) {
if (queue->front == NULL) {
return;
}
NODE* temp = queue->front;
queue->front = queue->front->next;
free(temp);
temp = NULL;
}
void destroy(QUEUE* queue) {
while (queue->front != NULL) {
dequeue(queue);
}
}
/*EOF*/