Given a Queue consisting of first n natural numbers (in random order). The task is to check whether the given Queue elements can be arranged in increasing order in another Queue using a stack in C. The operations allowed are:
#include <iostream>
#include<stack>
#include<queue>
using namespace std;
bool check_queue(int q_s, queue<int>& queue1)
{
stack<int> x;
int M = 1;
int get_first;
while (!queue1.empty()) {
get_first = queue1.front();
queue1.pop();
if (get_first == M)
M++;
else {
if (x.empty()) {
x.push(get_first);
}
else if (!x.empty() && x.top() < get_first) {
return false;
}
else
x.push(get_first);
}
while (!x.empty() && x.top() == M) {
x.pop();
M++;
}
}
if (M - 1 == q_s && x.empty())
return true;
return false;
}
int main()
{
cout<<"The first queue is:\n";
queue<int> F_Q;
F_Q.push(5);
F_Q.push(1);
F_Q.push(2);
F_Q.push(3);
F_Q.push(4);
int len = F_Q.size();
(check_queue(len, F_Q) ? (cout << "Yes\n") : (cout << "No\n "));
cout<<"The second queue is:\n";
queue<int> S_Q;
S_Q.push(5);
S_Q.push(1);
S_Q.push(2);
S_Q.push(6);
S_Q.push(3);
S_Q.push(4);
int len1 = S_Q.size();
(check_queue(len1, S_Q) ? (cout << "Yes\n") : (cout << "No\n "));
return 0;
}
Comments
Leave a comment