1 package com.datastack.stack;
2
3 import java.util.Arrays;
4
5 //栈
6 public class Stack {
7 private int max;
8 private int[] arr;
9 private int top = -1;
10
11 //构造器
12 public Stack(int max){
13 this.max = max;
14 arr = new int[this.max];
15 }
16 //栈满
17 public boolean isFull(){
18 return top == max-1;
19 }
20
21 //栈空
22 public boolean isEmpty(){
23 return top == -1;
24 }
25
26 //入栈
27 public void push(int value){
28 if(isFull()){
29 return;
30 }
31 arr[++top] = value;
32 }
33
34 //出栈
35 public int pop(){
36 if(isEmpty()){
37 throw new RuntimeException("栈空");
38 }
39 return arr[top--];
40 }
41
42 //打印栈
43 public void list(){
44 for(int i=top;i>=0;i--){
45 System.out.printf("stack[%d]=%d\n",i,arr[i]);
46 }
47 }
48
49 public static void main(String[] args) {
50 Stack stack = new Stack(3);
51 stack.push(1);
52 stack.push(2);
53 stack.push(3);
54 stack.push(4);
55 stack.push(5);
56 stack.list();
57
58 System.out.println(stack.pop());
59
60 stack.push(5);
61 stack.list();
62 }
63 }