用于插入链表的循环不起作用

问题描述 投票:0回答:1

我正在尝试在链接列表的末尾插入一些节点,但是此代码中有错误之处。

[我正在尝试进行循环,并希望借助该循环用户为列表输入所有数字,但我想我缺少了。

#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;
}
c linked-list singly-linked-list insertion function-definition
1个回答
0
投票

当为一个空列表调用该函数时,它仅在列表中插入一个元素并退出。

if(*ref==NULL)
   {
    *ref = temp;
    return;
   }

还请注意,为fflush调用stdin具有未定义的行为。

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
© www.soinside.com 2019 - 2024. All rights reserved.