繁体   English   中英

如何将链表与不同的结构链接起来

[英]How would you link a linked list with different struct

我有两种不同的结构

    typedef struct name {

    char*markerName;
    struct test *next;

}name_t;

 typedef struct test {

    int grade;
    int studentNumber;
    struct test *next;


}test_t;

和这个功能

void test(name_t* marker1,int data)
{
        test_t *temp= malloc(sizeof(test_t));
        test_t *location=NULL;
        temp->grade=data;
        temp->next=NULL;
        location=marker1->next;
        if(location==NULL)
        {
        //  printf("%i \n",temp->grade);
            marker1->next=temp;
        }
        else
        {
            while(location!=NULL)
            {
                printf("%i \n",location->grade);
                printf("%p \n",location->next);
                location=location->next;
            }
            location=temp;
        }
}

问题是我们正在创建一个stuct名称的数组,并在每个阵列的元素之后创建一个测试的链表。 如何将结构名称的节点链接到stuct测试?

我打印下一个,他们一直指向NULL指针。

您在链表的末尾超调。 对于您的location变量,您最终会得到“NULL”,即使它已被分配,它仍然是一个局部变量,当您的函数退出时它会脱离上下文。 你的while循环看起来应该更像这样:

while(location->next != NULL)
{
    printf("%i \n",location->grade);
    printf("%p \n",location->next);
    location = location->next;
}

location->next = temp;

严格地说,链表只能包含一种数据类型。 如果要包含包含两种结构类型的列表,可以使用union来模拟它:

struct name {
   char* markerName;
};

struct test {
   int grade;
   int studentNumber;
};

// Indicates the type of data stored in the union
enum dtype { NONE, NAME, TEST };

// Combination of the above structures, suitable for a mixed-type list
struct combo {
   struct combo*   next; // Next structure in the linked list
   enum dtype      type; // Indicates which of the union fields is valid
   union {
      struct name  name;
      struct test  test;
   };
};

这将两组数据存储在一个结构中,允许您从结构中创建列表,并使您能够跟踪当前有效的数据类型。

您可以使用指针键入void 当然,这假设您以某种方式知道下一个对象的类型。

当您想要创建异构数据结构时,只有一个结构类型的节点,在节点中有两个“有效负载”变量,一个告诉您节点的类型,以及一个指向结构的指针,可能更聪明一点。与实际数据。

具有两种类型的下一个指针的结构怎么样:一个类型为name_t,另一个类型为test_t。 您可以使用所需的链接,并将另一个留空。 我希望我能正确理解你的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM