public class Stack{
int[] data;
int maxSize;
int top;
public Stack(int maxSize) {
this.maxSize=maxSize;
data=new int[maxSize];
top=-1;
}

//入栈
public boolean push(int data) {
//入栈先判断栈中是否已满
if(top+1==maxSize) {
System.out.println("栈已满");
return false;
}
this.data[++top]=data;
return true;
}

//出栈
public int pop() throws Exception{
//出栈先判断栈是否已空
if(top==-1) {
throw new Exception("栈已空");
}
return this.data[top--];
}

public static void main(String[] args) throws Exception {
Stack stack=new Stack(1000);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
while(stack.top>=0) {
System.out.println(stack.pop());
}
}

}

posted on 2019-05-20 09:56  骑猪南下L  阅读(162)  评论(0编辑  收藏  举报