![]() |
VOOZH | about |
Given a Linked List, display the linked list in reverse without using recursion, stack or modifications to given list.
Examples:
Input: 1->2->3->4->5->NULL
Output: 5 4 3 2 1Input: 10->5->15->20->24->NULL
Output: 24 20 15 5 10
Below are different solutions that are now allowed here as we cannot use extra space and modify list.
1) Recursive solution to print reverse a linked list. Requires extra space.
2) Reverse linked list and then print. This requires modifications to original list.
3) Stack based solution to print linked list reverse. Push all nodes one by one to a stack. Then one by one pop elements from stack and print. This also requires extra space.
Algorithms:
1) Find n = count nodes in linked list. 2) For i = n to 1, do following. Print i-th node using get n-th node function
Output:
5 4 3 2 1
Time complexity: O(n2) where n is the number of nodes in the given linked list
Auxiliary Space: O(1), as constant extra space is required.