(Revise the MyStack class) Rewrite the MyStack class in Listing 11.10 to perform
ID: 3593002 • Letter: #
Question
(Revise the MyStack class) Rewrite the MyStack class in Listing 11.10 to perform a deep copy of the list field.
LISTING 11.10 MyStack.java 1 import java.util.ArrayList; 3 public class MyStack 4 private ArrayList list new ArrayList O; array list 6 public boolean isEmptyO stack empty? return 1ist.isEmpty 10 public int getSizeO get stack size return 1ist.size); 12 13 14 public Object peek O 15 16 peek stack return list.get(getizeO 1); 440 Chapter Inheritance and Polymorphism 17 18 public Object popO 19 20 21 Object o-list.get (getSize) - 1); list.remove(getSizeO) -1); return o 23 24 public void push(Object o) 25 26 27 28 0verride 29 public String toStringO 30 31 32 push list.add(o); return "stack: "list.toString);Explanation / Answer
# include<iostream.h>
# include<conio.h>
# define SIZE 20
class stack
{
int a[SIZE];
int tos; // Top of Stack
public:
stack();
void push(int);
int pop();
int isempty();
int isfull();
};
stack::stack()
{
tos=0; //Initialize Top of Stack
}
int stack::isempty()
{
return (tos==0?1:0);
}
int stack::isfull()
{
return (tos==SIZE?1:0);
}
void stack::push(int i)
{
if(!isfull())
{
cout<<"Pushing "<<i<<endl;
a[tos]=i;
tos++;
}
else
{
cerr<<"Stack overflow error !
Possible Data Loss !";
}
}
int stack::pop()
{
if(!isempty())
{
cout<<"Popping "<<a[tos-1]<<endl;
return(a[--tos]);
}
else
{
cerr<<"Stack is empty! What to pop...!";
}
return 0;
}
void reverse(stack s)
{
stack s2;
while(!s.isempty())
{
s2.push(s.pop());
}
cout<<"Reversed contents of the stack..."<<endl;
while(!s2.isempty())
{
cout<<s2.pop()<<endl;
}
}//end of fn.
void main()
{
clrscr();
stack s;
s.push(1);
s.push(2);
s.push(3);
reverse(s);
getch();
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.