![]() |
VOOZH | about |
Given a singly linked list. The task is to print the linked list in reverse order without actually reversing the linked list.
Examples:
Input: head : 1 -> 2 -> 3 -> 4 -> NULL
Output: 4 -> 3 -> 2 -> 1 -> NULLInput: head: 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output: 5 -> 4 -> 3 -> 2 -> 1 -> NULL
Table of Content
The idea is to use recursion to print the linked list in reverse order. Note that the question is only about printing the reverse , to reverse actual list please see this.
Below is the implementation of the above approach:
4 3 2 1
Time Complexity: O(n) , Where n is the number of nodes.
Auxiliary Space: O(n)
The idea is similar to the recursion , we can also perform printing in reverse order using a stack(iterative method). Store the values of the linked list in a stack. After traversing keep removing the elements from the stack and print them.
Below is the implementation of above approach:
4 3 2 1
Time Complexity: O(n) , As we are traversing the linked list only once.
Auxiliary Space: O(n)