gpt4 book ai didi

c - 为什么递归调用中使用while循环时程序会卡住

转载 作者:行者123 更新时间:2023-11-30 21:33:00 26 4
gpt4 key购买 nike

我编写了一个程序,将给定的十进制数转换为其数字的链接列表。当我执行下面的程序时,它挂起,但我不确定为什么?

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

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

struct node *convert_num(int num)
{
struct node *list = NULL;
while(num != 0)
{
list = malloc(sizeof(struct node));
list->data = num % 10;
list->next = convert_num(num/10);
}
return list;
}

int main()
{
struct node *n1;
n1 = convert_num(354);

return 0;

}

该程序挂起于 convert_num()功能。

最佳答案

您的函数有一个无限循环(numwhile (num != 0) { } 中永远不会改变)。修复:

struct node *convert_num(unsigned num)
{
if (num == 0)
return NULL;

struct node *list = malloc(sizeof(struct node));
list->data = num % 10;
list->next = convert_num(num/10);
return list;
}

struct node *convert_num(unsigned num)
{
struct node *head;
struct node **next_ptr = &head;
while (num != 0) {
*next_ptr = malloc(sizeof(struct node));
(*next_ptr)->data = num % 10;
next_ptr = &((*next_ptr)->next);
num /= 10;
}

*next_ptr = NULL;
return head;
}

关于c - 为什么递归调用中使用while循环时程序会卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45423862/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com