/****************************************************************************** * This program demonstrates the Stack ADT * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.pureprogrammer.Utils; public class ADTStack { static class IntegerStack { // Internal representation for the stack is a list private List stack = new ArrayList<>(); public IntegerStack() { stack = new ArrayList<>(); } public int pop() throws RuntimeException { if (stack.size() == 0) { throw new RuntimeException("Can't pop on empty stack!"); } return stack.remove(stack.size() - 1); } public void push(int value) { stack.add(value); } public int peek() throws RuntimeException { if (stack.size() == 0) { throw new RuntimeException("Can't peek on empty stack!"); } return stack.get(stack.size() - 1); } } public static void main(String[] args) { IntegerStack stack = new IntegerStack(); for (int x = 1; x <= 10; ++x) { stack.push(x); } try { System.out.println(stack.peek()); for (int x = 1; x <= 11; ++x) { System.out.println(stack.pop()); } } catch (RuntimeException ex) { System.out.println(Utils.exceptionMessage(ex)); } catch (Exception ex) { System.out.println("Unknown Exception!"); } } }