使用递归反转链表

Nyc*_*yck 5 c++ recursion reverse linked-list

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

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

还缺少的是将最后一个节点分配到 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;
    }
};
Run Code Online (Sandbox Code Playgroud)

ein*_*ica 2

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

尝试这个:

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;
}
Run Code Online (Sandbox Code Playgroud)

(未测试过...)