数组模拟栈
public class Stack {
Object[] objects=new Object[5];
int index=-1;
public void push(Object o) throws StackException {
if (index>=objects.length-1){
throw new StackException("栈已满");
}
objects[++index]=o;
System.out.println("压榨"+o+"成功"+",栈帧指向"+index);
}
public void pop() throws StackException {
if(index<0){
throw new StackException("栈已空");
}
System.out.println("弹栈"+objects[index]+"成功"+"栈帧指向"+index);
index--;
}
}
public class StackException extends Exception {
public StackException() {
}
public StackException(String s) {
super(s);
}
}
public class StackTest {
public static void main(String[] args) throws StackException {
Stack stack=new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
}
}
压榨1成功,栈帧指向0
压榨2成功,栈帧指向1
压榨3成功,栈帧指向2
压榨4成功,栈帧指向3
压榨5成功,栈帧指向4
Exception in thread "main" com.westore.stack.StackException: 栈已满
at com.westore.stack.Stack.push(Stack.java:8)
at com.westore.stack.StackTest.main(StackTest.java:11)
Exception in thread "main" com.westore.stack.StackException: 栈已空
at com.westore.stack.Stack.pop(Stack.java:15)
at com.westore.stack.StackTest.main(StackTest.java:12)