【发布时间】:2019-11-07 07:59:23
【问题描述】:
单链表的实现,统计链表中的节点数。 我已经编写了代码来计算单链表中的多个节点,它计数正确,但是如果我使用全局计数变量,则其他部分语句将执行 3 次,同样的事情正在发生。为什么会这样?我正在使用代码块编辑器,并且得到了上面提到的输出。 我不明白为什么 else 部分被执行了三遍。 请帮忙解决这个问题。
#include<stdio.h>
#include<stdlib.h>
struct data
{
int i;
struct data *next;
};
//int count;
struct data *head=NULL;
void insert(int d)
{
struct data *p;
if(head==NULL)
{
p=(struct data*)malloc(sizeof(struct data));
p->i=d;
p->next=NULL;
head=p;
}
else
{
p=(struct data*)malloc(sizeof(struct data));
struct data *temp;
temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=p;
p->i=d;
p->next=NULL;
}
}
void disp(struct data *temp)
{
if(temp==NULL)
{
return;
}
else
{
// printf("%d ",temp->i);//prints in forward direction
disp(temp->next);
printf("%d ",temp->i);//prints in reverse direction
}
}
void countL(struct data *c)
{
static int count;
if(c==NULL)
{
return;
}
else
{
count++;
countL(c->next);
}
printf("\n");
if(count==0)
{
printf("List is empty\n");
}
else
{
printf("Number of nodes in the linked list are:%d\n",count);
}
}
int main()
{
insert(1);
insert(2);
insert(3);
disp(head);
countL(head);
}
输出:
3 2 1
Number of nodes in the linked list are:3
Number of nodes in the linked list are:3
Number of nodes in the linked list are:3
我已经编写了代码来计算单链表中的节点数,它计数正确,但是如果我使用全局计数变量,则 else 部分语句将执行 3 次,同样的事情正在发生。为什么会这样?我正在使用代码块编辑器,我得到了上面提到的输出。
【问题讨论】:
-
这里有使用递归的要求吗?由于您在
insert函数中使用了 while 循环 (while(temp->next!=NULL)),我不明白为什么您的计数不会做同样的事情,即while (c != null) { count++; c = c->next; }。此外,您的计数函数(为什么countL中的“L”?)应该将计数作为值返回,而不是打印它。也许最大的问题是,count不应该是静态的 - 如果你连续两次调用countL,你会得到错误的值。 -
是的..谢谢..我正在学习数据结构,所以也尝试使用递归。
标签: c data-structures linked-list singly-linked-list