Give an implementation of the stack ADT using an array list for storage.
PROGRAM CODE:
import java.util.ArrayList;
import java.util.EmptyStackException;
public class Stack {
private ArrayList<Integer> stack;
public Stack() {
stack = new ArrayList<>();
}
// Check if the stack is empty
public boolean isEmpty() {
return stack.isEmpty();
}
// Push an element onto the top of the stack
public void push(int element) {
stack.add(element);
}
// Pop and return the top element from the stack
public int pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
return stack.remove(stack.size() - 1);
}
// Return the top element of the stack without removing it
public int peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return stack.get(stack.size() - 1);
}
// Return the number of elements in the stack
public int size() {
return stack.size();
}
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(5);
stack.push(10);
stack.push(15);
System.out.println("Stack size: " + stack.size());
System.out.println("Top element: " + stack.peek());
int poppedElement = stack.pop();
System.out.println("Popped element: " + poppedElement);
System.out.println("Stack size after pop: " + stack.size());
}
}
OUTPUT OF THE PROGRAM CODE:
Stack size: 3
Top element: 15
Popped element: 15
Stack size after pop: 2