c - 链接列表反向递归功能不起作用

标签 c list recursion reverse singly-linked-list

我无法弄清楚为什么我的递归函数不起作用。每次我运行代码时,链接列表都不会反向打印。

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/

相关文章:

c - gcc 中的嵌套函数使用 -std=c99

python - pandas:根据列表和另一列条件替换逗号分隔列中的相应值

python - 在python中使用xlrd从xls中提取数据

php - 来自只有 childids 的结构的递归数组

c - 搜索二叉树然后更新重复计数

c - 如何避免if语句?因为编译器无法将其优化为 simd

c - 这段 C 代码的作用是什么

c - 在 C 中的 vector 函数序列中避免(初学者)分配错误

python - 根据 bool 值列表过滤列表

python - 返回项的 PowerSet 的递归 Python 函数