簡體   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