In java: Write instance method bodies for the StringStack class, using the appro
ID: 668996 • Letter: I
Question
In java: Write instance method bodies for the StringStack class, using the approach that
position 0 in the array is the top of the stack.
public class StringStack
{
private String[] a; // the array to hold the items
private int n; // the current number of items in the stack
// construct an empty stack
public StringStack(){}
// place the given item on top of the stack
public void push( String s ){}
// return a reference to the top item
public String peek(){}
// remove the top item from the stack
public void pop(){}
// return the number of items in the stack
public int size(){}
}
Explanation / Answer
public class StringStack {
private static int MAX_SIZE = 4;
private String[] a; // the array to hold the items
private int n; // the current number of items in the stack
public static void main(String[] args) throws Exception{
StringStack st = new StringStack();
System.out.println("------------No of items in the stack - "+ st.size());
st.push("1");
st.display();
st.push("2");
st.display();
st.push("3");
System.out.println("No of items in the stack - "+ st.size());
System.out.println("Top item in the stack - "+ st.peek());
st.push("4");
st.display();
st.push("5");
st.display();
st.pop();
st.display();
st.pop();
st.display();
st.pop();
st.display();
st.pop();
st.display();
st.pop();
}
// construct an empty stack
public StringStack(){
n = 0;
a = new String[MAX_SIZE];
for(int i=0; i < MAX_SIZE; i++)
a[i]= ""; //Empty string
}
// place the given item on top of the stack
public void push( String s ){
if(n == MAX_SIZE)
System.out.println(" Pushing : "+s+" Stack is full");
else {
for(int i =n-1; i >=0; i--) {
a[i+1] = a[i];
}
a[0] = s;
n++;
}
}
// return a reference to the top item
public String peek(){
return a[0]; // 0-index element is the top element in the stack
}
// remove the top item from the stack
public void pop(){
if(n == 0)
System.out.println(" Stack is empty");
else {
int i =0;
for( i = 0; i < n-1; i++ ) {
a[i] = a[i+1];
}
a[i] ="";
n--;
}
}
public void display() {
System.out.println("Elements in the stack: "+n);
for(int i=0; i < n; i++)
System.out.print( a[i]+" ");
System.out.println();
}
// return the number of items in the stack
public int size(){
return n;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.