为什么其他部分要执行3次?

问题描述 投票:0回答:1

单链表的实现以计算链表中的节点数。我已经编写了代码以对单链接列表中的多个节点进行计数,它可以正确计数,但是如果我使用全局计数变量,则同一条语句也会执行part语句3次。为什么会这样呢?我正在使用代码块编辑器,并且得到上述输出。我不明白为什么其他部分要执行三次。请帮助解决此问题。

#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

我已经编写了用于对单链列表中的节点进行计数的代码,它可以正确计数,但是如果我使用全局计数变量,则同一条语句将执行part语句3次。为什么会这样呢?我正在使用代码块编辑器,并且得到上面提到的输出。

c data-structures
1个回答
2
投票

这是因为每次调用if都会无条件地进行打印else / countL。如果只想调用一次,则应将其移到if (c == NULL)内,以便仅在列表遍历终止时才调用:

void countL(struct data *c)
{
    static int count;
    if (c == NULL)
    {
        printf("\n");
        if (count == 0)
        {
            printf("List is empty\n");
        }
        else
        {
            printf("Number of nodes in the linked list are:%d\n", count);
        }
        return;
    }
    else
    {
        count++;
        countL(c->next);
    }
}

这样,您仅获得一次输出。

© www.soinside.com 2019 - 2024. All rights reserved.