数据结构-stack-顺序结构

86 阅读1分钟
static class Stack {
     private int[] table;

     private int top = -1;

     private int maxSize;

     private int size;

     private int incrementCapacity;

     private final static int STACK_DEFAULT_INIT_SIZE = 10;

     private final static int STACK_DEFAULT_INCREMENT_SIZE = 5;

     public Stack() {
         this.maxSize = STACK_DEFAULT_INIT_SIZE;
         this.table = new int[maxSize];
         this.size = 0;
         this.top = -1;
         this.incrementCapacity = STACK_DEFAULT_INCREMENT_SIZE;
     }

     /**
      * 入栈
      * @param value
      */
     public void push(int value) {
         if (isFull()) {
             ensureCapacity();
             table[++top] = value;
             size++;
         } else {
             table[++top] = value;
             size++;
         }
     }

     public int pop(){
         if (isEmpty()){
             throw new RuntimeException("you stack is empty");
         }
         int value = table[top--];
         size--;
         return value;
     }

     public int peek(){
         if (isEmpty()){
             throw new RuntimeException("you stack is empty");
         }
         int value = table[top];
         return value;
     }

     /**
      * 是否为空
      *
      * @return
      */
     public boolean isEmpty() {
         return top == -1;
     }

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

     /**
      * 扩容
      *
      * @return
      */
     public void ensureCapacity() {
         maxSize = maxSize + incrementCapacity;
         //复制
         int[] newTable = Arrays.copyOf(table, maxSize);
         table = newTable;
     }

 }