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

时间:2013-03-27 17:48:04

标签: c linked-list

我有两种不同的结构

    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指针。

4 个答案:

答案 0 :(得分:1)

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

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

location->next = temp;

答案 1 :(得分:1)

严格地说,链表只能包含一种数据类型。如果要包含包含两种结构类型的列表,可以使用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;
   };
};

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

相关问题