Problem Statement:
You are given a queue and an element k, you need to reverse the first ‘k’ elements in the queue.
Example
Input: Q = [1, 2, 3, 4, 5]
k = 3
Output: Q = [3, 2, 1, 4, 5]
Solution
We need to use additional stack to solve this problem.
Take a stack with the size ‘k’
Push the first ‘k’ elements into the stack.
Then we pop ‘k’ elements from stack, we will get the elements in reverse order and insert into queue.
Then rearrange the queue by popping n-k elements from the queue and inserting into the queue.
Example:
Input: Q = [1, 2, 3, 4, 5]
k = 3
Step 1:
Stack = 1, 2, 3
Queue = 4, 5
Step 2:
Queue = 4, 5, 3, 2, 1
Step 3:
Queue = 3, 2, 1, 4, 5
Pass
Solution in C++
#include <algorithm>
//visit www.ProDeveloperTutorial.com for 450+ solved questions
#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <stack>
using namespace std;
void reverse_Que(queue<int>* Queue , int k)
{
if(Queue->empty() == true || k > Queue->size() || k <= 0)
return;
stack<int> st;
for(int i=0 ; i<k ; i++)
{
st.push(Queue->front());
Queue->pop();
}
while(!st.empty())
{
Queue->push(st.top()),
st.pop();
}
for(int j=0 ; j<(Queue->size()-k) ; j++)
{
Queue->push(Queue->front());
Queue->pop();
}
}
int main(void)
{
queue<int> Q;
int K = 3;
Q.push(1);
Q.push(2);
Q.push(3);
Q.push(4);
Q.push(5);
reverse_Que(&Q , K);
cout<<"Queue = [ ";
while(!Q.empty())
{
cout<<Q.front()<<" ",
Q.pop();
}
cout<<"]";
return 0;
}
Output:
Queue = [ 3 2 1 4 5 ]