首页 > 解决方案 > 在链表中插入的循环不起作用

问题描述

我正在尝试在链表的末尾插入一些节点,但这段代码有些不对劲。

在这里,我正在尝试创建一个循环,并且在此循环的帮助下,我希望用户输入列表的所有数字,但我想我遗漏了一些东西。

#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;
}

标签: clinked-listsingly-linked-listinsertionfunction-definition

解决方案


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

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

还要注意 call fflushforstdin具有未定义的行为。

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

推荐阅读