用数组模拟栈

数组模拟栈

//表示栈
class ArrayStack{
    private int maxSize;//栈的大小
    private int[] stack; //数组模拟栈,数据放在该数组
    private int top = -1; //top表示栈顶,初始化-1,表示没有数据

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[maxSize];//初始化数组
    }

    //栈满
    public boolean isFull(){
        return top == maxSize-1;
    }
    //栈空
    public boolean isEmpty(){
        return top==-1;
    }
    //入栈push
    public void push(int value){
        if (isFull()){
            System.out.println("栈满了");
            return;
        }
        top++;
        stack[top] = value;
    }

    //出栈pop
    public int pop(){
        if (isEmpty()){
            throw new RuntimeException("栈空了");
        }
        int value = stack[top];
        top--;
        return value;
    }

    //遍历栈,遍历时需要从栈顶开始显示数据
    public void  list(){
        if (isEmpty()){
            System.out.println("栈空,没有数据");

        }
        for (int i = top; i >= 0 ; i--) {
            System.out.printf("stack[%d]=%d \n",i,stack[i]);
        }
    }
}

测试

 public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(4);
        String key = "";
        boolean loop = true;
        Scanner sc = new Scanner(System.in);

        while (loop){
            System.out.println("s(show):显示栈");
            System.out.println("e(exit):退出栈");
            System.out.println("p(push):添加栈");
            System.out.println("g(pop):拿出栈");
            key = sc.next();
            switch (key){
                case "s":
                    arrayStack.list();
                    break;
                case "e":
                    sc.close();
                    loop=false;
                    break;
                case "p":
                    System.out.println("请输入一个数字");
                    int value = sc.nextInt();
                    arrayStack.push(value);
                    break;
                case "g":
                    try {
                        int res = arrayStack.pop();
                        System.out.println("取出的数据为"+res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;

            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值