![]() |
VOOZH | about |
In C++, stacks are containers that store the elements in the last in-first out order(LIFO). In, this article, we will learn how we can reverse a stack in C++.
Example
Input: stack<int> S ={5,4,3,2,1} store Output: // Reversed Stack stack<int> S ={1,2,3,4,5}
We can reverse a stack in C++ using anther set or any other sequential data container. We just have to reverse the order of the elements present in the stack. The below approach shows how to reverse stack using another stack.
The following program illustrates how we can reverse a stack in C++:
Original stack: 5 4 3 2 1 Reversed stack: 1 2 3 4 5
Time Complexity: O(N) where N is the size of the stack.
Auxiliary Space: O(N)