【问题标题】:Inifinite recursion when executing function in C在 C 中执行函数时的无限递归
【发布时间】:2020-10-15 14:35:25
【问题描述】:

我尝试用 C 语言编写一个树程序,从插入函数开始,如下所示:

void insert(int val)
{
    struct node * nn = (struct node *)malloc(sizeof(struct node));
    nn->data = val;
    nn->left = NULL;
    nn->right = NULL;

    if(root == NULL)
    {
        root = nn;
    }

    else
    {
        struct node *ptr = root;

        while(ptr->left != NULL && ptr->right != NULL)
        {
            if(nn->data < ptr->data)
            {
                ptr = ptr->left;
            }

            else
            {
                ptr = ptr->right;
            }
        }

        if(ptr->data < nn->data)
        {
            ptr->right = nn;
        }

        else
        {
            ptr->left = nn;
        }
}

然后我编写了代码来显示这样形成的树的节点:

void display()
{
    struct node *n;
    
    if(root == NULL)
    {
        printf("Tree is Empty\n");
    }

    else
    {
        n = root;
        
        if(n!=NULL)
        {
            printf("%d",n->data);
            display(n->left);
            display(n->right);
        }    
    }
}

这是主要功能:

int main()
{
    int ch,val;

    while(ch!=3)
    {
        printf("1. Insert\n2. Display\n3. Exit\nEnter your choice: ");
        scanf("%d",&ch);

        switch(ch)
        {
            case 1:
            printf("Enter value to be inserted: ");
            scanf("%d",&val);
            insert(val);
            break;

            case 2:
            display();
            break;

            case 3:
            ch=3;
            printf("Exiting....\n");
            break;

            default:
            printf("Invalid choice, please try again\n");
            break;
        }
    }

    return 0;
}

但是当我在插入几个节点后尝试执行显示函数时,它只打印了无限循环中的第一个节点。

有人可以帮我解决这个问题吗?

【问题讨论】:

  • display(n-&gt;left);display 不需要任何参数。你的意思是void display(struct node *root) { ... }
  • 未成年人:Don't cast malloc result
  • 阅读您的 C 编译器(例如 GCC...)和调试器(例如 GDB)的文档。另请阅读 Modern CIntroduction to Algorithms
  • 请发布一个有效的 MCVE minimal reproducible example 以反映您正在运行的代码,否则我们将陷入无限无意义的错误追逐 - 即您将内容传递给 display(...) 而在此代码中不需要参数。
  • 这是开始学习如何使用调试器的绝佳机会。使用调试器进行编程比没有调试器要容易得多。

标签: c recursion


【解决方案1】:

每次迭代(递归)时,您都会再次从root 开始。当然,这将永远持续下去。

你的函数签名应该是

void display(struct node *n)

然后在 main 中调用它为:

display(root);

用我留给你的这个反馈来修复显示功能本身。


编辑:功能应该是:
void display(struct node *n)
{
    if (n) {
        printf("%d\n",n->data);
        display(n->left);
        display(n->right);
    }
}

【讨论】:

  • 应该是void display(struct node *root)n 已经在函数中定义了,反正OP谈到无限递归,所以我假设root是在文件范围内声明的或者是全局的,否则代码应该不编译。
  • @DavidRanieri ...并且该函数不需要n作为变量,而是作为参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
相关资源
最近更新 更多