我编写了一个程序来将给定的十进制数转换为其数字的链表。当我执行以下程序时,它会挂起,但我不确定为什么?
#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()
功能。
你的函数有一个无限循环(num
永远不会在while (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;
}