package 集合框架.stack;标签:arr,实现,top,System,stack,int,关于,public From: https://www.cnblogs.com/Gaze/p/18499632
public class Stack {
//存放数据
private int arr[];
private int top;
//数组容量
private int capacity;
Stack(int size){
arr = new int[size];
capacity = size;
top =-1;
}
public void push(int value) {
if (isFull()){
System.out.println("溢出\n中止程序");
System.exit(1);
}
arr[++top] = value;
System.out.println("压入元素"+value);
}
public int pop() {
if (isEmpty()){
System.out.println("数组为空\n中止程序");
//程序异常退出
System.exit(1);
}
return arr[top--];
}
public boolean isFull() {
return top == capacity - 1;
}
public boolean isEmpty(){
return top == -1;
}
public void printStack() {
for (int i = 0; i <= top; i++) {
System.out.println(arr[i]);
}
}
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
stack.printStack();
System.out.println("弹出");
stack.pop();
stack.printStack();
}
}