Problem Statement:
You are given a stack, reverse the stack using queue
Example:
Input: s = [1, 2, 3, 4]
Output q = [4, 3, 2, 1]
Solution Explanation:
Solution is very simple.
First push all the element from stack to queue.
Then push from queue to stack and get the result.
Time Complexity: O(1)
Space Complexity: O(1)
Code Solution
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
void solution(queue<int> &q)
{
stack<int> st;
while (!q.empty())
{
st.push(q.front());
q.pop();
}
while (!st.empty())
{
q.push(st.top());
st.pop();
}
}
void display(queue<int> q)
{
while(!q.empty())
{
cout<<q.front()<<" ";
q.pop();
}
cout<<endl;
}
int main()
{
queue<int> q;
for(int i=1; i<=5; i++)
{
q.push(i);
}
cout<<"Before reverse: ";
display(q);
solution(q);
cout<<"After reverse: ";
display(q);
}
Output
Before reverse: 1 2 3 4 5
After reverse: 5 4 3 2 1