用数组实现栈

class arrStack

package DataStructures.stack;

/**
 * 用数组模拟栈
 * @author coffee
 * @date 2021-03-30 17:00
 */
public class arrStack {
    private int maxSize;
    private int[] stack;
    private int top = -1;

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

    /**
     * 栈空
     * @return
     */
    public boolean isFull(){
        return top == maxSize -1;
    }

    /**
     * 栈空
     * @return
     */
    public boolean isEmpty(){
        return top == -1;
    }

    /**
     * 入栈
     * @param value
     */
    public void push(int value){
        if (isFull()){
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = value;
    }

    /**
     * 出栈
     * @return
     */
    public int pop(){
        if (isEmpty()){
            throw new RuntimeException("栈满");
        }
        int i = stack[top];
        top--;
        return i;
    }

    /**
     * 遍历栈
     */
    public void list(){
        if (isEmpty()){
            System.out.println("栈空");
            return;
        }
        for (int i = top; i >= 0 ; i--) {
            System.out.print(stack[i]);
        }
    }

    /**
     * 返回运算符的优先级,数字越大,优先级越高
     * @param ope
     * @return
     */
    public static int priority(int ope){
        if (ope == '*' || ope == '/'){
            return 1;
        }else if (ope == '+' || ope == '-'){
            return 0;
        }else
            return -1;
    }

    /**
     * 判断是否为运算符
     * @param ope
     * @return
     */
    public boolean isOpe(char ope){
        return ope == '+'||
                ope == '-' ||
                 ope == '*' ||
                  ope == '/';
    }

    /**
     * 计算方法
     * @param n1
     * @param n2
     * @param ope
     * @return
     */
    public int cal(int n1,int n2,int ope){
        int result = 0;
        switch (ope){
            case '+':
                result = n1 + n2;
                break;
            case '-':
                result = n2 - n1;
                break;
            case '*':
                result = n1 * n2;
                break;
            case '/':
                result = n2 / n1;
                break;
        }
        return result;
    }

    /**
     * 可以用来查看栈顶的值
     * @return
     */
    public int peek(){
        return stack[top];
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值