public class Pila {
private int top;
private final int MAX;
private int elem[];
private static final int MAXDEFAULT = 10;
//costruttori
public Pila() {
this(MAXDEFAULT);
}
public Pila(int max) {
top = 0;
MAX = max;
elem = new int[MAX];
}
//metodi "canonici"
public boolean IsFull() {
return top == MAX;
}
public boolean IsEmpty() {
return top == 0;
}
public void Clear() {
top = 0;
}
public void Push(int val) {
if (IsFull())
throw new StackFullException();
elem[top++] = val;
}
public int Pop() {
if (IsEmpty())
throw new StackEmptyException();
return elem[--top];
}
public int TopElem() {
if (IsEmpty())
throw new StackEmptyException();
return elem[top-1];
}
}
//Eccezioni personalizzate per la classe Pila.
class StackEmptyException extends RuntimeException {
public StackEmptyException() {
super("Pila vuota!!");
}
public StackEmptyException(String msg) {
super(msg);
}
}
class StackFullException extends RuntimeException {
public StackFullException() {
super("Pila piena!!");
}
public StackFullException(String msg) {
super(msg);
}
}