c - 在链表中插入的循环不起作用
问题描述
我正在尝试在链表的末尾插入一些节点,但这段代码有些不对劲。
在这里,我正在尝试创建一个循环,并且在此循环的帮助下,我希望用户输入列表的所有数字,但我想我遗漏了一些东西。
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
void insert(struct node** ref)
{ int n,i=0 ;
printf("how many numers:\n");
scanf("%d",&n);
fflush(stdin);
for(i=0;i<n;i++)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
struct node* last = *ref;
printf("enter the number:\n");
scanf("%d",&(temp->data));
fflush(stdin);
temp->next = NULL;
if(*ref==NULL)
{
*ref = temp;
return;
}
while(last->next != NULL)
last = last->next;
last->next = temp;
}
return;
}
int main()
{
struct node* head=NULL;
insert(&head);
return 0;
}
解决方案
当为一个空列表调用该函数时,它只在列表中插入一个元素并退出。
if(*ref==NULL)
{
*ref = temp;
return;
}
还要注意 call fflush
forstdin
具有未定义的行为。
fflush(stdin);
该函数可以通过以下方式定义
size_t insert( struct node **ref )
{
printf( "how many numbers: " );
size_t n = 0;
scanf( "%zu", &n );
if ( n != 0 )
{
while ( *ref != NULL )
{
ref = &( *ref )->next;
}
}
size_t i = 0;
for ( ; i < n && ( *ref = malloc( sizeof( struct node ) ) ) != NULL; i++ )
{
( *ref )->data = 0;
( *ref )->next = NULL;
printf( "enter the number: " );
scanf( "%d", &( *ref )->data );
ref = &( *ref )->next;
}
return i;
}
这是一个演示程序
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* next;
};
size_t insert( struct node **ref )
{
printf( "how many numbers: " );
size_t n = 0;
scanf( "%zu", &n );
if ( n != 0 )
{
while ( *ref != NULL )
{
ref = &( *ref )->next;
}
}
size_t i = 0;
for ( ; i < n && ( *ref = malloc( sizeof( struct node ) ) ) != NULL; i++ )
{
( *ref )->data = 0;
( *ref )->next = NULL;
printf( "enter the number: " );
scanf( "%d", &( *ref )->data );
ref = &( *ref )->next;
}
return i;
}
void display( struct node *head )
{
for ( ; head != NULL; head= head->next )
{
printf( "%d -> ", head->data );
}
puts( "null" );
}
int main(void)
{
struct node *head = NULL;
size_t n = insert( &head );
printf( "There are %zu nodes in the list. They are\n", n );
display( head );
return 0;
}
它的输出可能看起来像
how many numbers: 5
enter the number: 1
enter the number: 2
enter the number: 3
enter the number: 4
enter the number: 5
There are 5 nodes in the list. They are
1 -> 2 -> 3 -> 4 -> 5 -> null
推荐阅读
- reactjs - Reactjs Mobx @action 函数
- c# - 如何使用 C# 读取此文本文件并存储在列表中
- python - 在美国夏令时转换期间,Np.interp 在时间戳上无法正常工作
- ruby-on-rails - 根据条件将 Bootstrap 折叠设置为默认打开元素
- magento2 - Magento 2类别保存没有id = XXXX的实体
- asp.net-core - 尝试激活 RegisterModel 时无法解析 IEmailSender 类型的服务
- c - 在 C 中输入最多 256 个字符
- c - 扫描字符导致 devC 出现问题
- python - 如何为标准输入/标准输出创建异步流读取器/写入器?
- pandas - 将 Pandas DataFrame 转换为类似字节的对象