2. IatStack is a stack containing integer numbers. Write a segment of C++ code t
ID: 3600216 • Letter: 2
Question
2. IatStack is a stack containing integer numbers. Write a segment of C++ code to perform each of the following operations. You may call any of the member functions defined for the stack class and you may use additional stacks if necessary a) Set SecondElemet to the second element (from the top) in IatStack, leaving the stack without its top two elements b) Set Bottom equal to the bottom element in IntStack, leaving the stack empty. c) Set Bottom equal to the bottom element in IntStack, leaving the stack unchanged d) Remove all the zero elements from IntStack, leaving all the other elements in the stack.Explanation / Answer
IntStack ob;
(a)
// assuming that pop() also returns the top element
ob.pop();
int SecondElement = ob.pop();
(b)
int Bottom;
while(!ob.isEmpty())
{
Bottom = ob.pop();
}
(c)
IntStack temp;
int Bottom;
// loop untill the stack ob is empty
while(!ob.isEmpty())
{
Bottom = ob.pop();
// push the top element of ob into temp
temp.push(Bottom);
}
// add the contents of temp back to ob
// loop untill the stack temp is empty
while(!temp.isEmpty())
{
// push the top element of temp to ob
ob.push(temp.pop());
}
(d)
IntStack temp;
int x;
// loop untill the stack ob is empty
while(!ob.isEmpty())
{
x = ob.pop();
// push the top element of ob into temp
if(x != 0)
temp.push(x);
}
// add the contents of temp back to ob
// loop untill the stack temp is empty
while(!temp.isEmpty())
{
// push the top element of temp to ob
ob.push(temp.pop());
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.