我编写了一个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;
}
我认为在函数create
内的循环中>
for(i=1;i<n;i++)
您的意思
last = last->next;
代替
last=first;
请注意,将指向头节点的指针声明为全局且函数依赖于全局变量是一个坏主意。
此外,用户也可以将等于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