2017-07-31 43 views
-5

我已经编写了一个程序来将给定的十进制数转换为其数字的链表。当我执行下面的程序时,它会挂起,但我不知道为什么?为什么当while循环用于递归调用时程序卡住了

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

+8

'而(NUM!= 0)' - 它为什么会是'0'永远不会消失? –

+5

应该是'if'而不是'while'(或者你应该内联递归)。 – ikegami

+3

你不会改变循环内的数字 –

回答

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; 
}