c++ - 反转链表(通过递归)不起作用

标签 c++ c pointers linked-list heap-memory

我试图编写一段代码来反转链表,但得到了错误的输出。 有什么我想念的吗。

这是函数

void reverselinklist( struct node **headreverse)
{
    struct node *p = *headreverse;
    if(p->next == NULL)
    {
        *headreverse = p;
        return;
    }

    reverselinklist(&(p->next));
    p->next->next = p;
    p->next = NULL;

}

显示函数后

Input 409765
Output 4

最佳答案

*headreverse = p 没有意义。您应该每次都设置*headreverse = p->next 向前移动,直到到达最后一个节点。

无论如何,我更改了您的代码以使其工作:

void reverselinklist(struct node **headreverse)
{
    struct node *p = *headreverse;
    if(p->next == NULL){
        return;
    }
    *headreverse = p->next;
    reverselinklist(headreverse);
    p->next->next = p;
    p->next = NULL;
}

关于c++ - 反转链表(通过递归)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24133850/

相关文章:

c++ - 包含数据的全局静态类

c++ - OS X 使用箭头键移动终端插入符

c - 使用 fscanf 在 c 中读取文件

C++ 对象引用

c++ - 当模数为特殊形式时,通过模加法进行性能优化

c - Arduino Esplora 乒乓球游戏

c - function(&x) 中的指针 &x 是什么时候创建的?

C,通过函数中的指针赋值的问题

c++ - ';' token 之前的错误 : expected ',' , ')' 或 '='

c++ - 将现有 C 项目转换为 WPF