In: Computer Science
class ArrayStringStack { String stack[]; int top; public arrayStringStack(int size) { stack = new String[size]; top = -1; } //Assume that your answers to 3.1-3.3 will be inserted here, ex: // full() would be here //empty() would be here... //push() //pop() //displayStack() }
1. Write two boolean methods, full( ) and empty( ).
2. Write two methods, push( ) and pop( ). Note: parameters may be expected for push and/or pop.
3. Write the method displayStack( ) that prints the stack like a stack, from top to bottom.
In java
public class ArrayStringStack {
String stack[];
int top;
public ArrayStringStack(int size)
{
stack = new String[size];
top = -1;
}
// full() would be here
boolean full(){
// check top is equal size-1
return top==stack.length-1;
}
//empty()
boolean empty(){
// check top is -1 return true
return top==-1;
}
//push()
void push(String elem){
if(full()){ // check full print
System.out.println("Stack is full");
}else{ // add element to stack
stack[++top] = elem;
}
}
//pop()
void pop(String elem){
if(empty()){ // check empty
System.out.println("Stack is empty");
}else{ // decrease top
elem = stack[top];
top--;
}
}
void displayStack(){
// If stack is empty then return
if (empty())
return;
String x = stack[top];
String elem=""; // to store poped element
// Pop the top element of the stack
pop(elem);
// Print the stack element starting
// from top to bottom
System.out.println(x);
// Recursively call the function displayStack
displayStack();
// Push the same element onto the stack
// to preserve the order
push(x);
}
}
/* USE SCREENSHOT TO ALIGN CODE */
/* Driver class to test code */ (if want to check)
public class Driver {
public static void main(String[] args) {
// create object
ArrayStringStack s = new ArrayStringStack(5);
for (int i = 0; i < 5; i++) {
// convert i to string and add to stack
s.push(String.valueOf(i));
}
// print stack
s.displayStack();
}
}
/* OUTPUT */ TOP TO BOTTOM