簡體   English   中英

在C中,如何使用鏈表打印結構中的所有值,而該結構是嵌套的?

[英]In C, how to print all the values in struct by using linked-list, while this struct is nested?

我創建了兩個結構體和兩個變量 n1 和 n2,這是下面運行代碼時的結果:

10-nick-90.500000

20-威爾遜-100.500000。

我想要的是:

1.將elemtype變量值放入struct LNODE中。

2.使用printlist(LNDOE* head)打印值。

請幫我。

#include <stdio.h>
#include <stdlib.h>

typedef struct elemtype{
    int no;
    char* name;
    double score;
}elemtype;

typedef struct tagnode{
    elemtype data;
    struct tagnode* next;
}LNODE;

elemtype* print_elemtype(elemtype* data_to_print){
    elemtype* p = data_to_print;
    if ( p != NULL){
        printf("%d-%s-%lf", p->no,p->name,p->score);
    }
    printf("\n");
    return NULL;
}

void creat_link(LNODE** head, int n, void (*input)(elemtype*)){
    LNODE* s;
    *head = (LNODE*)malloc(sizeof(LNODE));
    (*head)->next = NULL;
    for(;n>0;n--){
        s = (LNODE*)malloc(sizeof(LNODE));
        input(&(s->data));
        s->next = (*head)->next;
        (*head)->next = s;
    }
}



int main()
{
    elemtype* n1 = malloc(sizeof(elemtype));
    elemtype* n2 = malloc(sizeof(elemtype));
    n1->name = "nick";
    n1->no = 10;
    n1->score = 90.5;
    n2->name = "wilson";
    n2->no = 20;
    n2->score = 100.5;

    elemtype** s1,**s2;
    s1 = &n1;
    s2 = &n2;

    print_elemtype(n1);
    print_elemtype(n2);

    
    
    free(n1);
    free(n2);
    n1 = NULL;
    n2 = NULL;
}

使用如下代碼在您的鏈表中爬行:

int main(void)
{
   struct_type *list = allocat_struct_type();
   struct_type *list_copy = list;  // always copy the head of the list when your manipulating the list

   while (list_copy != NULL) {
       printf("%s", list_copy->text_to_display); // text_to_display must be an str type in this exemple
       list_copy = list_copy->next;
   }
}

如果您仍然有問題,請精確定位何時何地。

隨意再次問我我希望它可以幫助你我試圖理解你會知道但它非常模糊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM