c - 在递归函数中使用 while

标签 c recursion linked-list

为了显示链接列表,我使用了递归函数。由于 while 循环,它正在运行无限循环。 当替换为“if”时,程序运行没有任何问题。

寻求有关使用的专家意见

while

在递归函数内。

<小时/>

带 while 的递归函数

     int display(node *curr){
             if((curr->next != NULL) ){ //<--replace "if" with "while" and it runs infinite loop
             printf("%d :: ",curr->data);
             display(curr->next);
             }
             return 0;
      }
<小时/>

具有创建和显示功能的完整代码

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>

struct node {
        int data;
        struct node *next;
};

typedef struct node node;

int create(node *head);
int display(node *head);

int main(int argc, char *argv[]){
        int ch,n=0;

        node *head,*tail,*current;
        head=(node*)malloc(sizeof(node));
        create(head);
        printf("\n");
        display(head);

        return 0;
}

int create(node *curr){
            int data;
            node *next;
            printf("Enter the Data Value (Enter -1 to Finish): ");
            scanf("%d",&data);
                    curr->data=data;
            if(data == -1)
            {
                    curr->next=NULL;

                    //return curr;
            }
            else
            {
                    curr->next=(node*)malloc(sizeof(node));
                    create(curr->next);
            }

            return 0; }

    int display(node *curr){
            if((curr->next != NULL) ){
                    printf("%d :: ",curr->data);
                    display(curr->next);
            }
            return 0; }

最佳答案

之所以不能使用 while(curr->next != NULL) 循环来索引并打印列表,是因为每次调用函数 display()curr->next 的值是常量。这看起来它将成功打印链接列表中的数据,然后无限地打印倒数第二个数据点,因为最后一个数据点的比较将不断失败。

按照 Ritwick Dey 的建议,使用

int display(node *curr) 
{ 
    while (curr) 
    {
        printf("%d",curr->data);
        curr = curr->next;
    }
}

应该适合你;通过更改当前节点的指针,您可以在每次迭代时修改 while 循环的条件。 NULL 值将导致此检查失败,因此您可以毫无问题地打印最终数据点。此实现的另一个好处是避免了递归函数调用的成本。

关于c - 在递归函数中使用 while,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40756736/

相关文章:

在stm32微 Controller 上创建虚拟UART

java - 我的程序中的一个错误。当我传递某个 int 时返回 -1 的递归方法

recursion - 结构感应的终止

c - 使用指针和两个结构数组进行桶排序

c - ATmega16 编程器寄存器不匹配

c - 为什么 GCC 不对无法访问的代码发出警告?

recursion - wget 使用 -r 和 -O - 挂起

c - 运行C程序时出现段错误

c - Valgrind:在 C 中释放链接列表时,大小 8 的读取无效

c - 用 C 写一个仿函数