gpt4 book ai didi

c - 使用循环将输入输入到链表中

转载 作者:太空宇宙 更新时间:2023-11-03 23:45:02 25 4
gpt4 key购买 nike

我制作这个程序是为了了解链表,因为我刚刚开始使用它们。该程序在“输入杀虫剂的数量”语句后立即终止(这是一项学校作业)。此外,我不确定如何将列表的长度限制在用户输入的大小范围内。

#include<stdio.h>

struct plants{
int val;
struct plants *next;
};

void printlist();

int main(){
struct plants* head = NULL;
struct plants* current= head;
head = malloc(sizeof(struct plants));
int counter,size;

printf("Enter the number of plants\n");

scanf("%d",&size);

printf("Enter the amount of pesticide each plant has.\n");

while(current!=NULL){
scanf("%d",current->val);
current= current->next;
}
return 0;
}

最佳答案

#include<stdio.h>
#include<malloc.h>

int main()
{
int count = 0;
int size = 0;
printf("Enter the number of plants\n");
scanf("%d",&size);

printf("Enter the amount of pesticide each plant has.\n");

您必须为 while 循环内的每个节点分配内存。如果您想在列表末尾添加新节点,请通过指向列表末尾指针的指针注意列表末尾。除此之外,您必须将要读取的值的地址传递给 scanf:

    struct plants * head = NULL;
struct plants ** current = &head; // current refers there, where next node has to be placed
while( count < size ) // do it for "size" nodes
{
*current = malloc(sizeof(struct plants)); // allocate memory for the node right to target
scanf( "%d", &((*current)->val)); // read the data
(*current)->next = NULL; // node is last node in list, so its successor is NULL
current = &((*current)->next); // step on forward
count ++; // increment number of nodes
}

请注意,由于 current 的类型是 struct plants ** 此代码将新节点放入列表的第一个元素的 head并为列表的所有其他节点转到 (*current)->next

将新节点添加到列表的头部会更容易:

    struct plants * head = NULL; // init head with NULL (this becomes end of the list)
while( count < size ) // do it for "size" nodes
{
struct plants * current = malloc(sizeof(struct plants)); // allocate memory for the node
scanf( "%d", &current->val); // read the data
current->next = head; // successor of node is head
head = current; // new node is head of list
count ++; // increment number of nodes
}

这将打印您的列表:

    struct plants *temp = head;
while( temp != NULL )
{
printf( "%d ", temp->val );
temp = temp->next;
}

不要忘记在程序结束时释放列表:

    while ( head != NULL )
{
struct plants *next = head->next;
free( head );
head = next;
}
return 0;
}

关于c - 使用循环将输入输入到链表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35392003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com