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.
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
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
- Print all paths from top left to bottom right in a matrix with four moves allowed
- Print Reverse a linked list using Stack
- Check if the elements of stack are pairwise sorted
- Check if stack elements are pairwise consecutive
- Design a stack to retrieve original elements and return the minimum element in O(1) time and O(1) space
- Stack Permutations (Check if an array is stack permutation of other)
- Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
- Print all possible combinations of r elements in a given array of size n
- Stack | Set 3 (Reverse a string using stack)
- Sort a stack using a temporary stack
- Count all possible paths from top left to bottom right of a mXn matrix
- Spaghetti Stack
- Reverse a number using stack
- Stack Class in Java
- How to create mergable stack?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : prerna saini