Hier leicht geändert:
[CODE=java]public class StackSpeicher<E> {
public static class StackSpeicherException extends Exception {
private static final long serialVersionUID = 1L;
}
public static class OverflowException extends StackSpeicherException {
private static final long serialVersionUID = 1L;
@Override
public String getMessage() {
return "Der Stapel ist voll!";
}
}
public static class UnderflowException extends StackSpeicherException {
private static final long serialVersionUID = 1L;
@Override
public String getMessage() {
return "Der Stapel ist leer!";
}
}
private class Node<T> {
private Node<E> next = null;
private E e = null;
private Node() {
}
private Node(Node<E> next, E e) {
this.next = next;
this.e = e;
}
}
private final static int MAX_HOEHE = 10;
private int aktuelleHoehe = 0;
private Node<E> top = null;
public void push(E daten) throws OverflowException {
if (aktuelleHoehe == MAX_HOEHE)
throw new OverflowException();
aktuelleHoehe++;
top = new Node<E>(top, daten);
}
public E pop() throws UnderflowException {
if (aktuelleHoehe == 0)
throw new UnderflowException();
aktuelleHoehe--;
E toReturn = top.e;
top = top.next;
return toReturn;
}
public E peek() throws UnderflowException {
if (aktuelleHoehe == 0)
throw new UnderflowException();
return top.e;
}
public boolean isEmpty() {
return aktuelleHoehe == 0;
}
public static void main(String[] args) throws StackSpeicherException {
StackSpeicher<String> ss = new StackSpeicher<>();
try {
String t = ss.peek();
System.out.println(t);
} catch (StackSpeicher.UnderflowException e) {
e.printStackTrace();
}
try {
String t = ss.pop();
System.out.println(t);
} catch (StackSpeicher.UnderflowException e) {
e.printStackTrace();
}
ss.push("0");
ss.push("1");
ss.push("2");
ss.push("3");
ss.push("4");
ss.push("5");
ss.push("6");
ss.push("7");
ss.push("8");
ss.push("9");
try {
ss.push("10");
} catch (StackSpeicher.OverflowException e) {
e.printStackTrace();
}
for ( ; !ss.isEmpty(); ) {
String t = ss.pop();
System.out.println(t);
}
try {
String t = ss.pop();
System.out.println(t);
} catch (StackSpeicher.UnderflowException e) {
e.printStackTrace();
}
System.out.println("ok");
}
}[/CODE]