如何在C中实现具有多个节点的链表?

时间:2022-09-28 14:32:54

I am making linked list(s) based on the user input as the following:

我根据用户输入制作链表,如下所示:

How Many employees? 4

Now, each one would have firstname lastname rate and zipcode, with a linked list I am trying to take these inputs and doing a for loop based on the number of records, but I am not doing it right obviously :

现在,每个人都会有firstname lastname rate和zipcode,带有链接列表我试图获取这些输入并根据记录数量进行for循环,但我显然没有做到这一点:

    struct records {
        char first[20];
        char last[20];
        float rate;
        int zip;
        struct node* next;
    };
    void main()
    {
        int i,n;
        printf("Please indicate the number of records : ");
        scanf("%d",&n);
        struct records *head,*conductor;
        head=(struct records*)malloc(n*sizeof(struct records));
        head->next=NULL;
        for (i=0;i<n;i++){
        printf("\nEnter employee information in the format :\nFirstname Lastname rate Zipcode (newline for the next)\n");
        scanf("%s %s %f %d",&head->first,&head->last,&head->rate,&head->zip);
        conductor=head;
        conductor=conductor->next;}
}

How do I get this right ?

我怎么做到这一点?

1 个解决方案

#1


1  

sample to fix

要修复的样本

struct records {
    char first[20];
    char last[20];
    float rate;
    int zip;
    struct records *next;//typo struct node* next; 
};
int main(void){//return type is `int`
    int i, n;
    printf("Please indicate the number of records : ");
    scanf("%d", &n);

    struct records *head,*conductor;
    head=(struct records*)malloc(n*sizeof(struct records));
    for (i=0; i<n; i++){
        printf("\nEnter employee information in the format :\nFirstname Lastname rate Zipcode (newline for the next)\n");
        scanf("%19s %19s %f %d", head[i].first, head[i].last, &head[i].rate, &head[i].zip);
        head[i].next = &head[i+1];
    }
    head[n-1].next = NULL;

    return 0;
}

#1


1  

sample to fix

要修复的样本

struct records {
    char first[20];
    char last[20];
    float rate;
    int zip;
    struct records *next;//typo struct node* next; 
};
int main(void){//return type is `int`
    int i, n;
    printf("Please indicate the number of records : ");
    scanf("%d", &n);

    struct records *head,*conductor;
    head=(struct records*)malloc(n*sizeof(struct records));
    for (i=0; i<n; i++){
        printf("\nEnter employee information in the format :\nFirstname Lastname rate Zipcode (newline for the next)\n");
        scanf("%19s %19s %f %d", head[i].first, head[i].last, &head[i].rate, &head[i].zip);
        head[i].next = &head[i+1];
    }
    head[n-1].next = NULL;

    return 0;
}