package 集合框架.stack;
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();
}
}