栈-用数组构建

思路如下~
在这里插入图片描述

在这里插入图片描述
下面直接上代码实操~

package datastructres.stack;

import com.sun.org.apache.bcel.internal.generic.NEW;

import java.util.Scanner;

/**
 * @author :Yan Guang
 * @date :Created in 2021/1/10 11:01
 * @description: 数组表示栈
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(4);
        Scanner scanner = new Scanner(System.in);
        int key = 0;
        boolean loop = true;

        while (loop) {
            System.out.println("1show表示展示栈");
            System.out.println("2push表示入栈");
            System.out.println("3pop表示出栈");
            System.out.println("4exit表示退出程序");
            System.out.println("请输入你的选择");
            key = scanner.nextInt();
            switch (key) {
                case 1:
                    stack.showStack();
                    break;
                case 2:
                    System.out.println("请输入一个数字");
                    int value = scanner.nextInt();
                    stack.push(value);
                    break;
                case 3:
                    try {
                        int res = stack.pop();
                        System.out.printf("出栈的数据是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 4:
                    scanner.close();
                    loop=false;
                    break;
            }
        }
        System.out.println("程序退出~");
    }

}

class ArrayStack {
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    public boolean isFull() {
        return top == maxSize - 1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public void push(int value) {
        if (isFull()) {
            System.out.println("栈满,无法添加~");
            return;
        }
        top++;
        stack[top] = value;
    }

    public int pop() {
        if (isEmpty()) {
            //throw相当于已经停止了代码,所以不用return
            //当存在返回值的时候(不为void)的时候,我们尽量可以抛出一个异常来代替return
            throw new RuntimeException("栈空,无法取出数据~");
        }
        int value = stack[top];
        top--;
        return value;
    }

    public void showStack() {
        if (isEmpty()) {
            System.out.println("栈已空~");
            return;
        }
        //循环的时候是从栈顶往下循环,也就是从数组的最后开始循环的~
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值