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;
}
};
this->head), in addition to the pointer to the next node? That seems non-standard (I'd expect each node to consist of just data and a pointer to the next node). You might want to include your node's structure in your question.