I'm working on some data structures in C. I have created a queue data structure that can take any type of data. This is currently being done by a macro which is default initialized to int
type.
#ifndef DATATYPE
#define DATATYPE int
#endif
The queue header is being included in another data structure - the binary search tree, and I am using the queue for a breadth-first-search implementation. In the Makefile, I have modified the DATATYPE
macro from an int
to a binary_tree_node_t *
type.
binary_tree: DEFS=-DDATATYPE="struct BINARY_TREE_NODE *"
My question is, is there a better way to do this using typedefs? Can I define a type DATATYPE
as an int
in the queue implementation, but have it get modified in a different header file?
Or is it possible to implement a queue that can take any datatype?
Here are the source files (redacted for sake of brevity) for reference:
queue.h
#ifndef _QUEUE_H
#define _QUEUE_H
#ifndef DATATYPE
#define DATATYPE int
#endif
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
typedef struct LL_NODE {
DATATYPE data;
struct LL_NODE* next;
} node_t;
typedef struct QUEUE {
node_t* head;
node_t* tail;
int size;
} queue_t;
queue_t* init_queue();
void destroy(queue_t* queue);
bool is_empty(queue_t* queue);
int size(queue_t* queue);
void enqueue(queue_t* queue, DATATYPE data);
DATATYPE dequeue(queue_t* queue);
DATATYPE peek(queue_t* queue);
#endif
binary_search_tree.c
#include "binary_search_tree.h"
void bfs_trav(binary_tree_node_t* root) {
queue_t* queue = init_queue();
binary_tree_node_t* temp = root;
enqueue(queue, root);
while (!is_empty(queue)) {
temp = dequeue(queue);
printf("%d ", temp->data);
if (temp->left) {
enqueue(queue, temp->left);
}
if (temp->right) {
enqueue(queue, temp->right);
}
}
destroy(queue);
return;
}
binary_search_tree.h
#ifndef _BINARY_SEARCH_TREE_H
#define _BINARY_SEARCH_TREE_H
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "../queue/queue.h"
typedef struct BINARY_TREE_NODE {
int data;
struct BINARY_TREE_NODE *left;
struct BINARY_TREE_NODE *right;
} binary_tree_node_t;
void bfs_trav(binary_tree_node_t* root);
#endif