package com.itguigu.myStack;
public class StackDemo {
public static void main(String[] args) {
int[] array = new int[3];
Stack stack = new Stack(array);
try {
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
} catch (Exception e) {
System.out.println(e.getMessage());
}
stack.show();
try {
System.out.println("出栈:" + stack.pop());
System.out.println("出栈:" + stack.pop());
// System.out.println("出栈:" + stack.pop());
// System.out.println("出栈:" + stack.pop());
} catch (Exception e) {
System.out.println(e.getMessage());
}
stack.show();
}
}
class Stack {
public int[] array;
public int rear = -1;
public Stack(int[] array) {
this.array = array;
}
public void push(int num) {
if (rear == array.length - 1) {
throw new RuntimeException("栈满~");
}
array[++rear] = num;
}
public int pop() {
if (rear == -1) {
throw new RuntimeException("栈空~");
}
return array[rear--];
}
public void show() {
if (rear == -1) {
System.out.println("栈空~, 无输出");
}
for (int i = rear; i >=0; i--) {
System.out.printf("array[%d]=%d\n", i, array[i]);
}
}
}
输出结果: