简单数组实现栈

/**
 * 数组实现栈
 */
public class ArrayStack {
    private int top;
    private int capacity;
    private int[] array;

    public ArrayStack() {
        this.top = -1;
        this.capacity = 1;
        this.array = new int[capacity];
    }

    public boolean isEmpty(){ // 判断栈是否为空
        //if the condition is true then 1 is returned else 0 is returned
        return (top == -1);
    }

    public boolean isStackFull(){ //判断栈是否为满
        return (top == array.length);
    }

    public void  push(int data){ //入栈操作
        if (isStackFull()){ // 判断栈是否已满, 栈满了则抛出栈满异常
            System.out.println("Stack Overflow");
        }else {
            array[++top] = data; //入栈
        }
    }

    public int pop(){ // 删除栈顶元素  
        if (isEmpty()) {
            System.out.println("Stack is Empty"); //栈为空则抛出空栈异常
            return 0;
        }else {
            return array[--top]; //出栈
        }
    }

    public void deleteStack(){ //删除栈
        top = -1;
    }

}

局限性:栈的最大空间必须预先声明且不能改变。试图对一个满栈执行入栈操作将产生一个针对简单数组这种特定实现栈方式的异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值