C++ Write the body for a function that replaces each copy of an item in a stack
ID: 3697070 • Letter: C
Question
C++ Write the body for a function that replaces each copy of an item in a stack with another item. Use the following specifications. (This function is in the client program.)
ReplaceItem (StackType& stack, ItemType oldItem, ItemType newItem)
function: Replace all occurrences of oldItem with newItem.
precondition: Stack has been initialized.
postcondition: Each occurrence of oldItem in stack has been replaced by newItem.
You may use any of the member functions of the nontemplate version of Stack-Type, but you may not assume any knowledge of the stack’s implementation.
Explanation / Answer
ReplaceItem (StackType& stack, ItemType oldItem, ItemType newItem)
{
//intiliazing objects
ItemType item;
StackType tempStack;
while (!Stack.IsEmpty())
{
Stack.Pop(item);
if (item==oldItem)
tempStack.Push(newItem);
else
tempStack.Push(item);
}
while (!tempStack.IsEmpty())
{
tempStack.Pop(item);
Stack.Push(item);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.