Inital commit
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
|
||||
interface Stack {
|
||||
|
||||
public void push(Object o) throws Exception;
|
||||
|
||||
public Object pop();
|
||||
|
||||
public Object peek();
|
||||
|
||||
public boolean isFull();
|
||||
|
||||
}
|
||||
|
||||
|
||||
class ArrayStack implements Stack {
|
||||
|
||||
Object[] ar;
|
||||
int index = 0;
|
||||
|
||||
public ArrayStack(int capacity) {
|
||||
|
||||
ar = new Object[capacity];
|
||||
|
||||
}
|
||||
|
||||
public void push(Object o) throws Exception {
|
||||
|
||||
if (!isFull()) {
|
||||
|
||||
ar[index] = o;
|
||||
index++;
|
||||
|
||||
}
|
||||
else throw new Exception("Stack is full.");
|
||||
|
||||
}
|
||||
|
||||
public Object pop() {
|
||||
|
||||
if (index > 0) {
|
||||
|
||||
index--;
|
||||
return ar[index];
|
||||
|
||||
}
|
||||
|
||||
// alternativ könnte man auch eine Exception werfen
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
public Object peek() {
|
||||
|
||||
if (index > 0) {
|
||||
|
||||
return ar[index-1];
|
||||
|
||||
}
|
||||
|
||||
// alternativ könnte man auch eine Exception werfen
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
// pre: index <= ar.length
|
||||
public boolean isFull() {
|
||||
return (index == ar.length);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Stack st = new ArrayStack(3);
|
||||
|
||||
try {
|
||||
st.push(new Integer(1));
|
||||
st.push(new Integer(2));
|
||||
st.push(new Integer(3));
|
||||
|
||||
// der wirft 'ne Exception
|
||||
st.push(new Integer(4));
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
System.out.println((Integer) st.pop());
|
||||
System.out.println((Integer) st.pop());
|
||||
|
||||
// die 1 kommt doppelt
|
||||
System.out.println((Integer) st.peek());
|
||||
System.out.println((Integer) st.pop());
|
||||
|
||||
// jetzt ist der Stack leer
|
||||
System.out.println((Integer) st.pop());
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user