Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
};
like image 522
Nyck Avatar asked Oct 16 '22 17:10

Nyck


1 Answers

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...)

like image 153
einpoklum Avatar answered Nov 03 '22 20:11

einpoklum