write a non-member, non-friend function(the function header is defined as below)
ID: 3673261 • Letter: W
Question
write a non-member, non-friend function(the function header is defined as below) to delete every occurrence of a specified item from a stack, leaving the order of the remaining items unchanged(assuming the stack is an integer stack):
void RemoveItem(stack & aStack, T item);
(Btw I am just a second semester student at my university and this is a level 2 computer science class so can you write it at a level to where it is not too advanced? This is a c++ question and it is ADT stack related.) Thanks.
Explanation / Answer
#include <iostream>
#include <stack>
using namespace std;
template <typename T>
void RemoveItem(stack<T> &aStack, T item)
{
stack<T> aux;
while(!aStack.empty())
{
if(aStack.top()!=item)
aux.push(aStack.top());
aStack.pop();
}
while(!aux.empty())
{
aStack.push(aux.top());
aux.pop();
}
}
template <typename T>
void printStack(stack<T> aStack)
{
while(!aStack.empty())
{
cout<<aStack.top()<<" ";
aStack.pop();
}
cout<<endl;
}
int main()
{
stack<int> myints;
for (int i=0; i<5; i++)
myints.push(i);
myints.push(2);
cout<<" Items in original stack are: ";
printStack(myints);
RemoveItem(myints,2);
cout<<" Items in modified stack are: ";
printStack(myints);
return 1;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.