Answer to Question #239788 in C for Sunil

Question #239788

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:

  1. Push and Pop elements in the stack
  2. Delete from the given Queue.
  3. Insert into another Queue.
1
Expert's answer
2021-09-22T23:43:58-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS