c++ - 使用递归反转链表

标签 c++ recursion linked-list reverse

我希望能够编写一个递归函数来反转链表。假设所有元素都已附加到列表中。

我想把head->next->next赋值给head,所以node->next的下一个节点就是节点本身。然后,当递归完成时,将链表的头(this->head)分配给最终节点(head)。

还缺少的是将最后一个节点的 next 分配给 NULL。

这样的东西在任何世界都行得通吗?它给出了运行时/段错误。

struct node {
    int data;
    node *next;
};

class LinkedList{
    node *head = nullptr;
public:
    node *reverse(node *head){
        if(head->next != nullptr){
            reverse(head->next)->next = head;
        }
        else{
            this->head = head;
        }
        return head;
    }
};

最佳答案

请注意,您忽略了 head 是 nullptr 本身的情况。此外,您不能只返回 head...您需要返回 reversed 列表的头部。

试试这个:

node* reverse_list(node* head) {
    if (head == nullptr or head->next == nullptr) { return head; }
    auto tail = head->next;
    auto reversed_tail = reverse_list(tail);
    // tail now points to the _last_ node in reversed_tail,
    // so tail->next must be null; tail can't be null itself        
    tail->next = head; 
    head->next = nullptr;
    return reversed_tail;
}

(未测试...)

关于c++ - 使用递归反转链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50656075/

相关文章:

c++ - 链接堆栈中的唯一指针

C++:从具有空字符的文件中读取

C++ 替换彼此相邻的空格

c++ - 计数排序的修改

java - 二分查找递归实现中的编译时错误

mysql - 这些 SQL 闭包表示例有什么区别?

c++ - 停止 p‌r‌o‌b‌l‌e‌m 是否意味着程序无法检查其他程序?

java - 堆栈溢出错误: How would I write this method Iteratively?

c - 不知道为什么我在这里遇到段错误

C链表-在末尾插入节点