我想创建一个可以在各种项目中使用的链接列表标题。需要的一项基本功能是我可以控制 main.c
中的链接列表类型。 main.c
可能看起来像这样:
#include "linkedlists.h"
#define NODE_TYPE int
int main() {
/* code using linked lists of integers */
return 0;
}
目前,我在 linkedlists.h
中定义类型,然后将其包含在 main.c
中,但这意味着我需要为每个项目。例如,在我当前的项目中,我在 linkedlists.h
中有这样的东西:
struct A {
char * name;
int age;
};
struct B {
char * name;
char * description;
char * schedule;
};
union node_type {
struct A a;
struct B b;
};
typedef struct node {
union node_type data;
struct node * next;
} node;
/* linked lists function declarations */
那么,如果可能的话,我怎样才能将列表类型规范移至 main.c
并使 linkedlists.h
对任何类型的列表都通用?
最佳答案
您必须从其“有效负载”中“抽象”列表,例如:
typedef struct node {
void *data; // the user's data
struct node *next;
} node;
您的链表函数现在只是将数据放在那里并将其返回给用户,而不知道该数据是什么。
// list.h
struct list;
int addNode(struct list *list, void *data); // add node with data to abstract list
void *getData(struct list *list); // return data from abstract list
和:
// list.c
struct node {
void *data; // the user's data
struct node *next;
};
struct list {
struct node *head, *current;
};
int addNode(struct list *list, void *data)
{
struct node *newNode= malloc(sizeof(struct node));
//...
// (add node to list)
newNode->data= data;
return SUCCESS;
}
关于c - 如何创建具有未定义类型的独立链接列表标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55762915/