In: Computer Science
In an application write a method filterStack that takes a stack
of integers as a parameter and filters its elements (in a new
Stack) in a way that places the even elements at the bottom and the
odd ones at the top. The original stack should remain
unchanged. You should use a queue (only
one queue) as a temporary storage. Use stack and queue
operations only to solve this problem. No need to
write the main method.
For example, if we apply the method filterStack to stack s1 below
then the method returns the stack s2.
#include<string>
#include<stack>
#include<queue>
#include<iostream>
using namespace std;
void filterStack(stack <int> mainStack)
{
queue<int> tempForOdd; //For storing odd
elements of stack
stack <int> newStack; // New stack in which
bottom elements are of even numbers and top will be odd numbers
while (mainStack.empty() != true)
{
int element =
mainStack.top();
mainStack.pop();
if (element % 2 == 0) //If even
we will push in new stack
{
newStack.push(element);
}
else
{
tempForOdd.push(element); // else if odd it will be pushed to queue
which is temproray storage
}
}
//As in queue we have odd elements and in newStack we
have all even elements
// Now we will push odd elements in newStack which
will be on top of the even numbers
while (tempForOdd.empty() != true)
{
int element = tempForOdd.front();
// It will tell the front element of queue
tempForOdd.pop();
// This will remove the front
element from queue and front will point to the next element
newStack.push(element);
}
//Printing newStack elements
int i = 1;
while (newStack.empty() != true)
{
cout << "element#" << i
<< "of filter Stack= " <<
newStack.top()<<endl;
newStack.pop();
}
}
//int main()
//{
// stack<int> test;
// int number;
//
// for (int i = 0; i < 10; i++)
// {
// cout << "Enter element#"
<< i + 1<<" ";
// cin >> number;
// test.push(number);
// }
//
// filterStack(test);
//}
COMMENT DOWN BELOW FOR ANY QUERIES AND,
LEAVE A THUMBS UP IF THIS ANSWER HELPS YOU.