In: Computer Science
3.1.1 Implement the pop() operation in the stack (1 mark) Implement a stack class named Stack2540Array using array. The starter code is as follows. The instance variables and most operations are provided. You need to implement the pop operation. Make sure that your program checks whether the stack is empty in the pop operation. The implementation can be found in the book and in our lecture slides.
import java . io .*;
import java . util .*;
public class Stack2540Array {
int CAPACITY = 128;
int top ;
String [] stack ;
public Stack2540Array () {
stack = new String [ CAPACITY ]; top = -1; } 1 3.1 Implement the stack ADT using array 3 TASKS public int size () { return top + 1; } public boolean isEmpty () { return ( top == -1) ; } public String top () {
if ( top == -1)
return null ;
return stack [ top ];
}
public void push ( String element ) {
top ++;
stack [ top ] = element ; }
IMPLEMENTED pop() OPERATION IN ABOVE STACK
public String pop() { // if the stack is empty if(top==-1) return null; String ans = stack[top]; top--; return ans; }
WHOLE PROGRAM WITH pop() FUNCTION :
import java . io .*; import java . util .*; class Stack2540Array { int CAPACITY = 128; int top; String[] stack; public Stack2540Array() { stack = new String[CAPACITY]; top = -1; } public int size() { return top + 1; } public boolean isEmpty() { return (top == -1); } public String top() { if (top == -1) return null; return stack[top]; } public void push(String element) { top++; stack[top] = element; } public String pop() { //if the stack is empty if(top==-1) return null; String ans = stack[top]; top--; return ans; } }