简体   繁体   English

使用递归反转链接列表

[英]Reversing Linked List using Recursion

I want to be able to write a recursive function to reverse a linked list. 我希望能够编写一个递归函数来反转链表。 Imagine that all the elements are already appended to the list. 想象一下,所有元素都已经附加到列表中。

I want to assign head->next->next to head, so the next node of node->next is the node itself. 我想在head旁边指定head-> next->,所以node-> next的下一个节点就是节点本身。 Then, when the recursion is done, assign the linked list's head (this->head) to the final node (which is head). 然后,当递归完成时,将链表的头部(this-> head)分配给最终节点(即head)。

What also is missing is assigning the final node's next to NULL. 还缺少的是将最后一个节点分配给NULL。

Will in any world something like this work? 在任何世界都会有这样的工作吗? It gives a runtime/segmentation error. 它给出了运行时/分段错误。

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;
    }
};

Note you're ignoring the case of head being nullptr itself. 请注意,你忽略了head为nullptr本身的情况。 Also, you can't just return head ... you need to return the head of the reversed list. 此外,你不能只返回head ...你需要返回反向列表的头部。

Try this: 试试这个:

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;
}

(not tested...) (未经测试......)

List reversing function must be tail-recursive, otherwise it is going to overflow the stack when recursing over a long list. 列表反转函数必须是尾递归的,否则在递归长列表时它会溢出堆栈。 Eg: 例如:

node* reverse(node* n, node* prev = nullptr) {
    if(!n)
        return prev;
    node* next = n->next;
    n->next = prev;
    return reverse(next, n);
}

An iterative list reversion can be inlined more easily: 可以更轻松地内联迭代列表返回:

inline node* reverse(node* n) {
    node* prev = nullptr;
    while(n) {
        node* next = n->next;
        n->next = prev;
        prev = n;
        n = next;
    }
    return prev;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM