[Approach] Using Iterative Method - O(n) Time and O(1) Space
The idea is to reverse the linked list by changing the direction of links using three pointers: prev, curr, and next. At each step, point the current node to its previous node and then move all three pointers forward until the list is fully reversed.
Output
5 -> 4 -> 3 -> 2 -> 1
[Alternate Approach 1] Using Recursion Method- O(n) Time and O(n) Space
The idea is to use recursion to reach the last node of the list, which becomes the new head after reversal. As the recursion starts returning, each node makes its next node point back to itself, effectively reversing the links one by one until the entire list is reversed.
Output
5 -> 4 -> 3 -> 2 -> 1
[Alternate Approach 2] Using Stack - O(n) Time and O(n) Space
The idea is to traverse the linked list and push all nodes except the last node into the stack. Make the last node as the new headof the reversed linked list. Now, start popping the element and append each node to the reversed Linked List. Finally, return the head of the reversed linked list.