栈的实现

来源:互联网 发布:python 字符串替换两个 编辑:程序博客网 时间:2024/06/05 09:37

栈:先进后出

用数组实现栈

public classMyStack {

    //底层实现是一个数组

    private long[] arr;

    private int top;

   

    /**

     * 默认的构造方法

     */

    public MyStack() {

        arr = newlong[10];

        top = -1;

    }

   

    /**

     * 带参数构造方法,参数为数组初始化大小

     */

    public MyStack(int maxsize) {

        arr = newlong[maxsize];

        top = -1;

    }

   

    /**

     * 添加数据

     */

    public void push(int value) {

        arr[++top] = value;

    }

   

    /**

     * 移除数据

     */

    public long pop() {

        returnarr[top--];

    }

   

    /**

     * 查看数据

     */

    public long peek() {

        returnarr[top];

    }

   

    /**

     * 判断是否为空

     */

    public boolean isEmpty() {

        returntop == -1;

    }

   

    /**

     * 判断是否满了

     */

    public boolean isFull() {

        returntop == arr.length - 1;

    }

}

 

public classTestMyStack {

    public static void main(String[] args) {

        MyStackms = newMyStack(4);

        ms.push(23);

        ms.push(12);

        ms.push(1);

        ms.push(90);

        System.out.println(ms.isEmpty());

        System.out.println(ms.isFull());

       

        System.out.println(ms.peek());

        System.out.println(ms.peek());

       

        while(!ms.isEmpty()) {

            System.out.print(ms.pop() +",");

        }

       

        System.out.println(ms.isEmpty());

        System.out.println(ms.isFull());

    }

}

运行结果:

    false

true

90

90

90,1,12,23,true

false

 

0 0
原创粉丝点击