我如何在 c 中的许多列表的节点中拥有结构?

How can I have structs in the nodes of many lists in c?

下面有这段代码,我希望结构中的变量数据包含另一个结构。例如,我希望我的数据是 3 个其他变量(源、目标和时间),以便列表中的每个节点在其中有 3 个不同的位置。我怎样才能让它成为可能?

typedef struct Node 
{
 char data;
 struct Node *next;
} Node;

int push_front( Node **head, char data )
{
 Node *new_node = malloc( sizeof( Node ) );
 int success = new_node != NULL;

 if ( success )
 {
    new_node->data = data;
    new_node->next = *head;
    *head = new_node;
 }

 return success;
}

多种方法,您可以将成员添加到节点结构(适合您的情况的最佳解决方案):

typedef struct Node {
    int src, dst, time;
    struct Node *next;
} Node;

使您的数据成为一个结构体:

struct Data {
    int src, dst, time;
};

typedef struct Node {
    struct Data data; /* can also be a pointer */
    struct Node *next;
};

在你的结构中创建一个结构:

typedef struct Node {
    
    struct {
        int src, dst, time;
    } data;

    struct Node *next;
};

你可以让数据结构匿名(迂腐的ansi会抱怨) 并在未封装时像第一个示例中那样访问成员。当你在结构中有一个联合时,这样做更有用。

typedef struct Node {
    
    struct {
        int src, dst, time;
    };

    struct Node *next;
};

现在您的函数可能类似于以下之一:

 int push_front( Node **head, int src, int dst, int time );
 int push_front( Node **head, struct Data data /* can be a pointer */);
 int push_front( Node **head, struct {int src, dst, time;} data );