![]() |
VOOZH | about |
Given a stack s, the task is to print the elements of the stack from bottom to top, such that the elements are still present in the stack without their order being changed in the stack.
Examples:
Input : | 4 | | 3 | | 2 | | 1 | |________| Output :1 2 3 4
Approach 1 (Recursion): The idea is to pop the element of the stack and call the recursive function PrintStack. Once the stack becomes empty start printing the element which was popped last and the last element that was popped was the bottom-most element. Thus, elements will be printed from bottom to top. Now push back the element that was printed, this will preserve the order of the elements in the stack.
Below is the implementation of the above approach:
1 2 3 4
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach 2 (Using another stack): The idea is to push every element into another temporary stack and then print elements of the temporary stack.
1 2 3 4
Time Complexity: O(N)
Auxiliary Space: O(N)