In: Computer Science
Consider the following statements:
linkedStackTypemtack; linkedQueueType queue; int num;
Suppose the input is
28 30 15 11 10 -9 21 8 -3 33 17 14
Write a C++ code that processes these numbers as follows: If the number is an even number, it is pushed onto the stack. If the number is odd and divisible by 3, it is added into the queue; otherwise the top element, if any, of the stack is removed and the square of the number is added onto the stack. After processing these numbers, what is stored in stack and queue?
please with details, do not copy from the book, thank you
//Following is the required C++ program
#include <bits/stdc++.h>
using namespace std;
void showstack(stack <int> s) //function to show
stack
{
while (!s.empty())
{
cout << '\t'
<< s.top();
s.pop();
}
cout << '\n';
}
void showqueue(queue <int> q) //function to show
queue
{
while (!q.empty())
{
cout << '\t'
<< q.front();
q.pop();
}
cout << '\n';
}
int main(){
int n;
cout<<"Enter number of elements in the
input: ";
cin>>n; //Taking number of elements in the
input
stack<int>s; //declaring the stack
queue<int>q; //declaring the queue
int i,x;
cout<<"Enter "<<n<<" elements:
";
for(i=0;i<n;i++){ //loop to input every
element
cin>>x;
//checking the
conditions and pushing into stack or queue
if(x%2==0){
s.push(x);
}else if(x%2==1
&& x%3==0){
q.push(x);
} else
if(!s.empty()){
int sq = s.top();
s.pop();
s.push(sq*sq);
}
}
//showing the stack and queue
cout << "The stack is : ";
showstack(s);
cout << "The queue is : ";
showqueue(q);
}
Sample Run:
Hope this helped. Please do upvote and if there are any queries please ask in comments section.