![]() |
VOOZH | about |
Given a linked list, print the reverse of it without modifying the list.
Examples:
Input : 1 2 3 4 5 6 Output : 6 5 4 3 2 1 Input : 12 23 34 45 56 67 78 Output : 78 67 56 45 34 23 12
Below are different solutions that are now allowed here as we cannot use extra space and modify the list.
In this post, the efficient stack-based solution is discussed.
Note: Instead of inserting data from each node into the stack, insert the node's address onto the stack. This is because the size of the node's data will be generally more than the size of the node's address. Thus, the stack would end up requiring more memory if it directly stored the data elements. Also, we cannot insert the node's data onto the stack if each node contained more than one data member. Hence, a simpler and efficient solution would be to simply insert the node's address.
Below is the implementation of the above idea:
5 4 3 2 1
Time complexity: O(N) where N is number of nodes of linked list
Auxiliary Space: O(n)