1、源码

ArrayStack类

  1. package com.study.stack;
  2. public class ArrayStack {
  3. private int maxsize;
  4. private int[] stack;
  5. private int top = -1;
  6. public ArrayStack(int maxsize) {
  7. this.maxsize = maxsize;
  8. stack = new int[this.maxsize];
  9. }
  10. //栈满
  11. public boolean isFull(){
  12. return top == maxsize-1;
  13. }
  14. //栈空
  15. public boolean isEmpty(){
  16. return top == -1;
  17. }
  18. //入栈
  19. public void push(int value){
  20. if (isFull()){
  21. System.out.println("栈满");
  22. }
  23. top++;
  24. stack[top] = value;
  25. }
  26. //出栈
  27. public void pop(){
  28. if (isEmpty()){
  29. throw new RuntimeException("栈空");
  30. }
  31. int value = stack[top];
  32. top--;
  33. System.out.println(value);
  34. }
  35. //显示栈
  36. public void show(){
  37. if (isEmpty()){
  38. System.out.println("栈空");
  39. }
  40. for (int i=top;i>=0;i--){
  41. System.out.println(stack[i]);
  42. }
  43. }
  44. }

ArrayStackDemo测试类

package com.study.stack;

public class ArrayStackDemo {

    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(5);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        System.out.println("===========");
        stack.pop();
        System.out.println("==============");
        stack.show();
    }

}

测试结果
图片.png