I had done the reverse of linked list using recursion, but how the pointer actually working a bit confused.
If I swap statements 1 and 2 in the below code the program will not run Why? Because I assume (*head)->next = nullptr
will set *temp = nullptr
so there is no meaning of (*temp)->next = *head
, but if this true then in the below code even after statement 1 (*head)->next
is set to nullptr so it should set the *temp equals to nullptr and according to that it should not reverse the linked list but actually the code reverse the linked list How?
void push(struct node*& tail, int v)
{
struct node* newNode = new node;
newNode->data = v;
newNode->next = tail;
tail = newNode;
}
void reverse_ll3(struct node* *rootAddress, struct node* *head, struct node* *temp)
{
if(!(*temp))
{
*rootAddress = *head;
return;
}
reverse_ll3(rootAddress, &((*head)->next), &((*temp)->next));
(*temp)->next = *head; // --------------1
(*head)->next = nullptr; // --------------2
}
int main()
{
struct node* head = NULL;
struct node* curr;
push(head, 60);
push(head, 50);
push(head, 40);
push(head, 30);
push(head, 20);
push(head, 10);
print_list(head);
cout << endl;
curr = head;
reverse_ll3(&head,&curr,&(curr->next));
print_list(head);
cout << endl;
return 0;
}