栈的实现

栈:先进后出

用数组实现栈

public classMyStack {

    //底层实现是一个数组

    private long[] arr;

    private int top;

   

    /**

     * 默认的构造方法

     */

    public MyStack() {

        arr = new long[10];

        top = -1;

    }

   

    /**

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

     */

    public MyStack(int maxsize) {

        arr = new long[maxsize];

        top = -1;

    }

   

    /**

     * 添加数据

     */

    public void push(int value) {

        arr[++top] = value;

    }

   

    /**

     * 移除数据

     */

    public long pop() {

        return arr[top--];

    }

   

    /**

     * 查看数据

     */

    public long peek() {

        return arr[top];

    }

   

    /**

     * 判断是否为空

     */

    public boolean isEmpty() {

        return top == -1;

    }

   

    /**

     * 判断是否满了

     */

    public boolean isFull() {

        return top == 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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值