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 email@example.com. 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
- Find maximum in a stack in O(1) time and O(1) extra space
- Design a stack that supports getMin() in O(1) time and O(1) extra space
- Print reverse of a Linked List without extra space and modifications
- Stack | Set 3 (Reverse a string using stack)
- Find pair for given sum in a sorted singly linked without extra space
- Reverse a number using stack
- Reverse a stack using recursion
- Reverse the Sentence using Stack
- Length of longest palindrome list in a linked list using O(1) extra space
- Print Reverse a linked list using Stack
- Program to reverse a linked list using Stack
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- 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
- Sort a stack using a temporary stack
- Find extra node in the second Linked list
- Clone a linked list with next and random pointer in O(1) space