Solved by recursion and simple approach
#include <bits/stdc++.h>
void reverse(LinkedListNode<int>*&head, LinkedListNode<int>*prev,LinkedListNode<int>* curr){
if(curr == NULL){
// Set the head to the last node reached, which is the new head of the reversed list
head = prev;
return;
}
LinkedListNode<int>*forward = curr->next; // Store the next node
reverse(head,curr,forward); // Recursive call with updated pointers
curr -> next = prev; // Reverse the link
}
// Main function to reverse the linked list
LinkedListNode<int> *reverseLinkedList(LinkedListNode<int> *head)
{
LinkedListNode<int>* prev = NULL;
LinkedListNode<int> *curr = head;
reverse(head,prev,curr);
return head;
//Second approach to solve.
/*
LinkedListNode<int>* prev = NULL;
LinkedListNode<int> *curr = head;
while(curr!= NULL){
LinkedListNode<int>*next = curr->next;
curr->next = prev;
prev =curr;
curr = next;
}
return prev;
*/
}