c - 如何创建具有未定义类型的独立链接列表标题

标签 c types linked-list

我想创建一个可以在各种项目中使用的链接列表标题。需要的一项基本功能是我可以控制 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/

相关文章:

ios - 来自 UI 控件的奇怪 Bool 类型

types - 为什么 Elm 使用 '++' 运算符来连接字符串?

memory-management - 在动态存储分配和释放期间使用循环链表作为 "free list"v/s 平衡二叉搜索树

c - 如何处理输出结构中的字符串分配

c - 如何通过 ctrl+C 或 ctrl+Z 杀死父进程及其子进程

c - 关于无符号整数下溢的 C 行为问题

java - 使用 equals() 查看字符串是否具有 LinkedList 中提供的关键字

c - 以给定大小的组反转链表

将数组转换为 memcpy 的指针

c++ - 如何在字符串中使用符号?