数组实现栈

/**
* 数组实现栈
*
* @author heweihao
* @date: 2021/3/25 11:08
*/
public class ArrayStack {
   /**
    * 栈的大小
    */
   private final int maxSize;
   /**
    * 栈数组
    */
   private int[] stack;
   
   /**
    * 栈顶指针,指向栈顶元素
    * 初始在栈低
    */
   private int top = -1;

   public ArrayStack(int maxSize) {
       this.maxSize = maxSize;
       stack = new int[maxSize];
  }

   /**
    * 入栈
    */
   public void push(int num) {
       if (isFull()) {
           System.out.println("栈满。");
           return;
      }
       top++;
       stack[top] = num;
  }

   /**
    * 出栈
    */
   public int pop() {
       if (isEmpty()) {
           throw new RuntimeException("栈空");
      }
       int value = stack[top];
       top--;
       return value;
  }

   /**
    * 显示栈列表,遍历时从栈顶取数据
    */
   public void list() {
       if (isEmpty()) {
           throw new RuntimeException("栈空");
      }
       for (int i = top; i > -1;i--) {
           System.out.printf("stack[%d]=%d\n",i,pop());
      }
  }

   /**
    * 栈满
    */
   public boolean isFull() {
       return top == maxSize - 1;
  }

   /**
    * 栈空
    */
   public boolean isEmpty() {
       return top == -1;
  }
}

 

posted @ 2021-03-31 16:05  北辰南风  阅读(222)  评论(0)    收藏  举报