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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With