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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Print Bottom-Right View of a Binary Tree
- Print all paths from top left to bottom right in a matrix with four moves allowed
- Find maximum sum from top to bottom row with no adjacent diagonal elements
- Print Reverse a linked list using Stack
- Print leaf nodes in binary tree from left to right using one stack
- Delete all even elements from a stack
- Check if the elements of stack are pairwise sorted
- Sort the given stack elements based on their modulo with K
- 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
- Find maximum in stack in O(1) without using additional stack
- Print all possible combinations of r elements in a given array of size n
- Sort a stack using a temporary stack
- Stack | Set 3 (Reverse a string using stack)
- Bottom-up traversal of a Trie
- Count all possible paths from top left to bottom right of a mXn matrix
- Sum of nodes in bottom view of Binary Tree
- Minimum cost to reach from the top-left to the bottom-right corner of a matrix
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.