I have to write a function to reverse a linked list using recursion in C++. I did it and the reasoning seems correct to me, but the code is not working. Could someone explain me why? Thank you all!
This is the function:
list* reverseList(list* head, list* p, list* n){
if(head->next == NULL){
head->next = p;
p = head;
head = n;
n = NULL;
return head;
}
else{
head->next = p;
p = head;
head = n;
n = n->next;
return reverseList(head, p, n);
}
}
This is the list struct:
struct list{
int val;
list *next;
};
This is the main:
int main() {
list *head, *p1, *p2, *prev, *next;
head = new list;
head->val = 1;
p1 = new_node(head, 2);
p2 = new_node(p1, 3);
p2->next = NULL;
print_list(head);
prev = NULL;
next = head->next;
reverseList(head, prev, next);
print_list(head);
return 0;
}
And these are other functions i use to create new nodes with values and to print the list:
list* new_node(list* old_node, int value)
{
old_node->next = new list;
old_node->next->val = value;
return old_node->next;
}
void print_list(list* head){
while(head != NULL){
cout << head->val << endl;
head = head->next;
}
}
mainand post a snip-it that can be copied, compiled and run. How to create a Minimal, Complete, and Verifiable example*pis a pointer butpis just a local to function won't make any changes at calling functionprint_list(p2);The head is no longer the head after you reverse it. `