How to Reverse a Vector Using a Stack in C++?
Last Updated :
09 Feb, 2024
In C++, the stack container follows the LIFO (Last In First Out) order of operation. It means that the element first inserted will come out at last while the element that was last inserted will come out first. In this article, we will learn how we can use stack to reverse a vector in C++
Example
Input: myVector = {1,2,3,4,5}
Output: Reversed Vector: 5 4 3 2 1
Reverse a Vector Using Stack in C++
We can use the std::stack to reverse the elements of the vector using the following algorithm.
- First, create a stack and push all the elements in the stack one by one.
- Once all elements of a vector are pushed, start traversing the vector and replacing the vector element with the top of the stack. Then pop that element from the stack.
- Keep doing it till the stack is empty.
C++ Program to Reverse a Vector Using Stack
The below program demonstrates how we can reverse a vector using a stack.
C++
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
void reverseVectorUsingStack(vector< int >& vec)
{
stack< int > auxStack;
for ( const auto & element : vec) {
auxStack.push(element);
}
for ( auto & element : vec) {
element = auxStack.top();
auxStack.pop();
}
}
int main()
{
vector< int > numbers = { 1, 2, 3, 4, 5 };
cout << "Original Vector: " ;
for ( const auto & num : numbers) {
cout << num << " " ;
}
reverseVectorUsingStack(numbers);
cout << "\nReversed Vector: " ;
for ( const auto & num : numbers) {
cout << num << " " ;
}
return 0;
}
|
Output
Original Vector: 1 2 3 4 5
Reversed Vector: 5 4 3 2 1
Time Complexity: O(N), where N is the number of elements in the vector.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...