Open In App

How to Reverse a Vector Using a Stack in C++?

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to reverse a vector using stack
  
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
  
void reverseVectorUsingStack(vector<int>& vec)
{
  
    // creating a auxilliary stack to store elements of
    // vector temporarily
    stack<int> auxStack;
  
    // Push elements onto the stack
    for (const auto& element : vec) {
        auxStack.push(element);
    }
  
    // Pop elements from the stack to reverse the vector
    for (auto& element : vec) {
        element = auxStack.top();
        auxStack.pop();
    }
}
  
int main()
{
    vector<int> numbers = { 1, 2, 3, 4, 5 };
  
    // Before reversal
    cout << "Original Vector: ";
    for (const auto& num : numbers) {
        cout << num << " ";
    }
  
    // Reverse the vector using the stack
    reverseVectorUsingStack(numbers);
  
    // After reversal
    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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads