带求最小值的堆栈算法

来源:互联网 发布:谢谢 歌词 知乎 编辑:程序博客网 时间:2024/05/17 03:30

packagemin_stack;

 

/**

 *@authorzhou shengshuai

 *

 */

classStackWithMin {

    intsize;

    int[]arr;

    intpos;

 

    /**

     *@paramsize

     */

    publicStackWithMin(int size) {

          this.size = size;

          arr = new int[size];

          pos = -1;

    }

 

    publicvoidpush(int value) {

          arr[++pos] = value;

    }

 

    publicintpop() {

          if(!isEmpty()) {

              int pope =arr[pos--];

              System.out.println("The Pop element is: " + pope);

              return pope;

          } else

              return -1;

    }

 

    publicintpeek() {

          returnarr[pos];

    }

 

    publicbooleanisEmpty() {

          if(pos < 0) {

              System.out.println("Stack is Empty!");

              returntrue;

          } else

              returnfalse;

    }

 

    publicintmin() {

          intmin =arr[0];

 

          for(int i = 1; i <=pos; i++) {

              if (min >arr[i]) {

                   min = arr[i];

              }

          }

 

          returnmin;

    }

 

}

 

 

publicclassStackWithMinTest {

 

    /**

     *@paramargs

     */

    publicstaticvoidmain(String[] args) {

          StackWithMin swm = newStackWithMin(6);

 

          swm.push(5);

          swm.push(2);

          swm.push(7);

          swm.push(6);

          swm.push(1);

          swm.push(8);

 

          System.out.println("The Min element is: " + swm.min());

 

          swm.pop();

          swm.pop();

          swm.pop();

          swm.pop();

          swm.pop();

          swm.pop();

          swm.pop();

    }

 

}

 

原创粉丝点击