栈的数组实现

栈是一个先入后出的有序数据结构(FILO)

栈的操作操作只能是在栈顶(Top)或者栈底(Bottom)进行

声明:下面的代码只是一个最基础的实现,没有经过严格的测试。

/**
 * 使用数组模拟栈
 */
public class MyArrayStack<E> {
    private int top=-1;
    private int maxSize;
    private Object[] arr;

    public MyArrayStack(int maxSize) {
        this.maxSize = maxSize;
        arr=new Object[maxSize];
    }

    //判断栈是否已经满了
    public boolean isFull(){
        //top相当于数组的下标
        return top==maxSize-1;
    }

    public boolean isEmpty(){
        return  top==-1;
    }
    //入栈
    public  void push(E e){
        if(isFull()){
            throw  new RuntimeException("栈空间已满!");
        }
        top++;
        arr[top]=e;
    }

    //出栈,每次只取栈顶的第一个元素
    public E  pop(){
        if(isEmpty()){
            throw  new RuntimeException("栈为空!");
        }
        E e=(E)arr[top];
        top--;
        return e;
    }

    public void show(){
        for (Object o : arr) {
            System.out.println(o.toString());
        }
    }


    public static void main(String[] args) {


        MyArrayStack<String> myArrayStack = new MyArrayStack(5);
        myArrayStack.push("110");
        myArrayStack.push("220");
        myArrayStack.push("330");
        myArrayStack.push("440");
        myArrayStack.push("550");

        System.out.println(myArrayStack.pop());
        System.out.println(myArrayStack.pop());
        System.out.println(myArrayStack.pop());
        System.out.println(myArrayStack.pop());
        System.out.println(myArrayStack.pop());

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值