在递归调用中使用while循环时为什么程序被卡住了

时间:2017-07-31 19:29:02

标签: c linked-list

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

#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()函数中挂起。

1 个答案:

答案 0 :(得分:5)

你的函数有一个无限循环(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;
}