【问题标题】:Why else part is getting executed 3 times?为什么其他部分被执行3次?
【发布时间】: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-&gt;next!=NULL)),我不明白为什么您的计数不会做同样的事情,即 while (c != null) { count++; c = c-&gt;next; }。此外,您的计数函数(为什么 countL 中的“L”?)应该将计数作为值返回,而不是打印它。也许最大的问题是,count 不应该是静态的 - 如果你连续两次调用 countL,你会得到错误的值。
  • 是的..谢谢..我正在学习数据结构,所以也尝试使用递归。

标签: c data-structures linked-list singly-linked-list


【解决方案1】:

这是因为每次调用countL 时都会无条件地打印if/else。如果你只想调用一次,你应该把它移到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);
    }
}

这样你只得到一次输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 2015-04-07
    • 2014-05-16
    • 2013-01-27
    相关资源
    最近更新 更多