【问题标题】:How can I have structs in the nodes of many lists in c?如何在 c 中的许多列表的节点中拥有结构?
【发布时间】:2022-01-05 13:55:44
【问题描述】:

我在下面有这段代码,我希望结构中的变量数据包含另一个结构。例如,我希望我的数据是 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;
}

【问题讨论】:

  • 只需添加一个结构成员。但是为什么它必须是一个嵌套结构呢?只需给你的结构更多成员。
  • @Cheatah 不是意味着对于我结构中的每个新成员,我都会采用一个新节点吗?

标签: c list struct


【解决方案1】:

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

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 );

【讨论】:

  • 非常有帮助,感谢您的宝贵时间!我会尝试所有方法,看看哪种方式我能处理得最好。
  • 插入节点后如何显示列表?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
  • 1970-01-01
  • 2015-03-01
  • 2021-01-18
相关资源
最近更新 更多