Как подсчитать количество узлов в связанном списке? Почему на выходе отображается количество узлов как «2»? - PullRequest
2 голосов
/ 16 марта 2020

Я написал программу c, чтобы найти количество узлов в списке ссылок. Но проблема возникает из-за того, что значение счетчика, которое я печатаю, получается равным 2

Мой точный вывод выглядит как ->

ЧИСЛО УЗЛОВ 2

Что я здесь не так делаю?

//the code for the program is here:-

#include<stdio.h>
#include<stdlib.h>

struct node
{
 int data;
 struct node *next;
}*first=NULL;

void create(int a[],int n)
{
 struct node *t,*last;
 first=(struct node *)malloc(sizeof(struct node));
 first->data=a[0];
 first->next=0;
 last=first;
 int i;
 for(i=1;i<n;i++)
 {
  t=(struct node *)malloc(sizeof(struct node));
  t->data=a[i];
  t->next=NULL;
  last->next=t;
  last=first;
 }
}

void count(struct node *p) //function to count number of nodes
{
 int count=0;
 while(p!=NULL)
 {
  count++;
  p=p->next;
 }
 printf("Number of nodes are %d ",count);
}

int main()
{
 int a[]={1,2,3,4};
 create(a,4);
 count(first);
 return 0;
}

1 Ответ

3 голосов
/ 16 марта 2020

Я думаю, что в l oop внутри функции create

for(i=1;i<n;i++)

вы имеете в виду

last = last->next;

вместо

last=first;

Pay обратите внимание на то, что плохая идея объявлять указатель на головной узел как глобальный и когда функции зависят от глобальных переменных.

Также пользователь может передать в функцию количество элементов массива, равное 0. Также может произойти сбой выделения памяти.

Я бы объявил функцию следующим образом

size_t create( struct node **head, const int a[], size_t n )
{
    // if the list is not empty free its nodes
    while ( *head != NULL )
    {
        struct node *current = *head;
        *head = ( *head )->next;
        free( current );
    }

    size_t i = 0;

    for ( ; i < n && ( *head = malloc( sizeof( struct node ) ) ) != NULL; i++ )
    {
        ( *head )->data = a[i];
        ( *head )->next = NULL;

        head = &( *head )->next;
    }

    return i;
}

И вызывать функцию как

size_t n = create( &first, a, sizeof( a ) / sizeof( *a ) );

В этом случае функция возвращает количество созданных узлов в списке.

Вот демонстрационная программа.

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

size_t create( struct node **head, const int a[], size_t n )
{
    // if the list is not empty free its nodes
    while ( *head != NULL )
    {
        struct node *current = *head;
        *head = ( *head )->next;
        free( current );
    }

    size_t i = 0;

    for ( ; i < n && ( *head = malloc( sizeof( struct node ) ) ) != NULL; i++ )
    {
        ( *head )->data = a[i];
        ( *head )->next = NULL;

        head = &( *head )->next;
    }

    return i;
}

void output( const struct node *head )
{
    for ( ; head != NULL; head = head->next )
    {
        printf( "%d -> ", head->data );
    }

    puts( "null" );
}

int main(void) 
{
    struct node *head = NULL;

    int a[] = { 1, 2, 3, 4 };
    const size_t N = sizeof( a ) / sizeof( *a );

    size_t n = create( &head, a, N );

    printf( "There are %zu nodes in the list\n", n );

    printf( "They are " );

    output( head );

    return 0;
}

Его выход

There are 4 nodes in the list
They are 1 -> 2 -> 3 -> 4 -> null
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...