【发布时间】:2020-06-27 13:15:58
【问题描述】:
我编写了一个 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;
}
【问题讨论】:
-
OT:使用可变宽度字体时,缩进宽度会丢失 1 个字符。建议每个缩进级别使用 4 个空格
-
OT:关于:
first=(struct node *)malloc(sizeof(struct node));和t=(struct node *)malloc(sizeof(struct node));1) 在 C 中,返回的类型是void*,可以分配给任何指针。强制转换只会使代码混乱。建议拆除石膏。 2) 调用任何堆分配函数时:malloc()calloc()和/或realloc()始终检查 (!=NULL) 返回值以确保操作成功。 3)分配的内存在退出程序前没有传递给free(),导致内存泄漏 -
OT:关于:
struct node { int data; struct node *next; }*first=NULL不要隐藏指针。而是将结构定义与结构的实例分开。这可以提高代码的清晰度和灵活性
标签: c data-structures struct linked-list singly-linked-list