简体   繁体   中英

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. Then, when the recursion is done, assign the linked list's head (this->head) to the final node (which is head).

What also is missing is assigning the final node's next to 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. Also, you can't just return head ... you need to return the head of the reversed list.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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