l oop для вставки в связанный список не работает - PullRequest
1 голос
/ 06 мая 2020

Я пытаюсь вставить несколько узлов в конец связанного списка, но что-то не так в этом коде.

Здесь я пытаюсь сделать al oop и с помощью этого l oop Я хочу, чтобы пользователь ввел все числа для списка, но я думаю, что что-то упустил.

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

1 Ответ

0 голосов
/ 06 мая 2020

Когда функция вызывается для пустого списка, она вставляет только один элемент в список и завершает работу.

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
...