Reverse a Stack without using recursion and extra space. Even the functional Stack is not allowed.
Input : 1->2->3->4 Output : 4->3->2->1 Input : 6->5->4 Output : 4->5->6
We have discussed a way of reversing a string in below post.
The above solution requires O(n) extra space. We can reverse a string in O(1) time if we internally represent the stack as a linked list. Reverse a stack would require a reversing a linked list which can be done with O(n) time and O(1) extra space.
Note that push() and pop() operations still take O(1) time.
Original Stack 4 3 2 1 Reversed Stack 1 2 3 4
This article is contributed by Niharika Sahai. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Clone a stack without extra space
- Print reverse of a Linked List without extra space and modifications
- Design a stack that supports getMin() in O(1) time and O(1) extra space
- Find maximum in a stack in O(1) time and O(1) extra space
- Find pair for given sum in a sorted singly linked without extra space
- Stack | Set 3 (Reverse a string using stack)
- Find maximum in stack in O(1) without using additional stack
- Length of longest palindrome list in a linked list using O(1) extra space
- Sort a stack using a temporary stack
- Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
- Reverse a number using stack
- Program to reverse a linked list using Stack
- Print Reverse a linked list using Stack
- Java Program to Reverse a String using Stack
- Reverse the Words of a String using Stack
- Reverse a stack using recursion
- Design a stack to retrieve original elements and return the minimum element in O(1) time and O(1) space
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- Check for balanced parenthesis without using stack
- Stack Permutations (Check if an array is stack permutation of other)