Question: Java: Add following methods to ISimpleStack interface and modify classes FixedLengthStack and DynamicStack: void reset ( ) / / empty the stack, char peek (

Java: Add following methods to ISimpleStack interface and modify classes FixedLengthStack and DynamicStack: void reset()//empty the stack, char peek()// like pop() but char remains on the stack, int size()//the number of chats currently on the stack.
public interface ISimpleStack {
void push(char ch);
char pop();
boolean isEmpty();
boolean isFull();
}
class FixedLengthStack implements ISimpleStack {
private char[] data;
private int tos;
FixedLengthStack(int size){
data = new char[size];
tos =0;
}
FixedLengthStack(FixedLengthStack otherStack){
data = new char[otherStack.data.length];
tos = otherStack.tos;
for(int i =0; i < tos; i++)
data[i]= otherStack.data[i];
}
FixedLengthStack(char[] chrs){
data = new char[chrs.length];
tos =0;
for(char ch: chrs)
push(ch);
}
public void push(char ch){
if(isFull()){
System.out.println("-- Stack is full.");
return;
}
data[tos]= ch;
tos++;
}
public char pop(){
if(isEmpty()){
System.out.println("-- stack is empty.");
return (char)0;
}
tos--;
return data[tos];
}
public boolean isEmpty(){
return tos ==0;
}
public boolean isFull(){
return tos == data.length;
}
}
class DynamicStack implements ISimpleStack {
private char[] data;
private int tos;
DynamicStack(int size){
data = new char[size];
tos =0;
}
DynamicStack(DynamicStack otherStack){
data = new char[otherStack.data.length];
tos = otherStack.tos;
for(int i =0; i < tos; i++)
data[i]= otherStack.data[i];
}
DynamicStack(char[] chrs){
data = new char[chrs.length];
tos =0;
for(char ch: chrs)
push(ch);
}
public void push(char ch){
if(tos == data.length){
char[] t = new char[data.length *2];
for(int i =0; i < tos; i++)
t[i]= data[i];
data = t;
}
data[tos]=ch;
tos++;
}
public char pop(){
if(isEmpty()){
System.out.println("-- Stack is empty.");
return (char)0;
}
tos --;
return data[tos];
}
public boolean isEmpty(){
return tos ==0;
}
public boolean isFull(){
return false;
}
}
class ISimpleStackDemo {
public static void main(String[] args){
int i;
char ch;
ISimpleStack iStack;
FixedLengthStack fixedStack = new FixedLengthStack(10);
DynamicStack dynStack = new DynamicStack(5);
iStack = fixedStack;
for(i =0; !iStack.isFull(); i++)
iStack.push((char)('A'+ i));
System.out.println("Contents of fixedStack: ");
while(!iStack.isEmpty()){
ch = iStack.pop();
System.out.print(ch);
}
System.out.println();
iStack = dynStack;
for(i =0; i <26; i++)
iStack.push((char)('A'+ i));
System.out.print("Contents of dynStack: ");
while(!iStack.isEmpty()){
ch = iStack.pop();
System.out.print(ch);
}
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!