我无法弄清楚为什么我的递归函数不起作用。每次我运行代码时,链接列表都不会反向打印。
typedef struct numberline NUMBERLINE;
NUMBERLINE * startptr;
NUMBERLINE * newptr;
NUMBERLINE * curptr;
NUMBERLINE *revRecursive(NUMBERLINE *curptr)
{
NUMBERLINE *q, *head;
if(curptr->next == NULL)
{
return curptr;
}
head = curptr;
q = curptr = revRecursive(curptr);
while(q->next != NULL)
{
q = q->next;
q->next = head;
head->next = NULL;
return curptr;
}
}
也许我在参数中使用了错误的指针,或者我不确定是否正确实现。
最佳答案
该函数可以如下所示
NUMBERLINE * reverse( NUMBERLINE *head )
{
if ( head && head->next )
{
NUMBERLINE *current = head;
head = head->next;
head = reverse( head );
current->next->next = current;
current->next = NULL;
}
return head;
}
至于你的函数定义,甚至这个语句
if(curptr->next == NULL)
{
return curptr;
}
当curptr
等于NULL
时出现未定义的行为。
关于c - 链接列表反向递归功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57272791/