在这里插入图片描述

栈实现中缀表达式综合计算器

/**
 * @author:zmc
 * @function:
 * @date: 2020/10/6 19:36
 */
public class ArrayStack {

    public static void main(String[] args) {
        String expression = "13-9/3+4";
        Stack numStack = new Stack(10);
        Stack operStack = new Stack(10);
        int index = 0;
        int num1 = 0;
        int num2 = 0;
        int oper = 0;
        int res = 0;
        char ch = ' ';
        //用于拼接
        String keepNum = "";
        while(true){
            ch = expression.substring(index,index+1).
                    charAt(0);
            if(operStack.isOper(ch)){
                if(!operStack.isEmpty()){
                    if(operStack.priority(ch) <= operStack
                            .priority(operStack.peek())){
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        oper = operStack.pop();
                        res = numStack.cal(num1,num2,oper);
                        numStack.push(res);
                        operStack.push(ch);
                    }
                    //如果当前操作符的优先级大于栈顶优先级 直接入栈
                    else {
                        operStack.push(ch);
                    }
                }
                //操作符栈为空则直接入栈
                else {
                    operStack.push(ch);
                }
            }else {
                keepNum += ch;
                if(index == expression.length() - 1){
                    numStack.push(Integer.parseInt(keepNum));
                }else {
                    if(operStack.isOper(expression.substring(index + 1,index + 2).charAt(0))){
                        numStack.push(Integer.parseInt(keepNum));
                        keepNum = "";
                    }
                }
            }
            index++;
            if(index >= expression.length()){
                break;
            }
        }

        //表达式扫描完毕,将操作数和符号出栈
        while(true){
            if(operStack.isEmpty()){
                break;
            }
            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            if(!operStack.isEmpty() && operStack.peek() == '-'){
                num1 = -1 * num1;
            }
            res = numStack.cal(num1,num2,oper);
            numStack.push(res);
        }
        System.out.println("结果竟然是:"+numStack.pop());
    }
}
class Stack{
    private int maxSize;
    private int[] stack;
    //栈顶
    private int top = -1;

    public Stack(int maxSize){
        this.maxSize = maxSize;
        stack = new int[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()){
            System.out.println("栈空");
            throw new RuntimeException("栈空");
        }
        return stack[top--];
    }

    public void list(){
        if(isEmpty()){
            return;
        }
        for(int i = top; i >= 0; i--){
            System.out.println(stack[i]);
        }
    }

    public int priority(int oper){
        if(oper == '*' || oper == '/'){
            return 1;
        }else if(oper == '+' || oper == '-'){
            return 0;
        }else {
            return -1;
        }
    }

    public boolean isOper(char val){
        return val == '+' || val == '-' || val == '*'
                || val == '/';
    }

    public int cal(int num1, int num2, int oper){
        int res = 0;
        switch (oper){
            case '+':
                res = num1 + num2;
                break;
            case '-':
                res = num2 - num1;
                break;
            case '*':
                res =  num2 * num1;
            break;
            case '/':
                res =  num2 / num1;
            break;
            default:
                break;
        }
        return res;
    }

    public int peek(){
        return stack[top];
    }
}

栈实现后缀表达式综合计算器

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author:zmc
 * @function:
 * @date: 2020/10/11 13:34
 */
public class PolanNotation {
    public static void main(String[] args) {
        String suffixExpression = "3 4 + 5 * 6 -";
        List<String> list = getListString(suffixExpression);
        System.out.println(calculate(list));

        String expression = "1+((2+3)*4)-5";
        List<String> strings = toInfixExpressionList(expression);
        System.out.println(strings);

        List<String> strings1 = parseSuffixExpressionList(strings);
        System.out.println(strings1);
        System.out.println(calculate(strings1));
    }

    public static List<String> toInfixExpressionList(String s){
        List<String> ls = new ArrayList<>();
        int i = 0;
        StringBuilder str;
        char c;
        do{
            if((c = s.charAt(i)) < '0' || (c = s.charAt(i)) > '9'){
                ls.add("" + c);
                i++;
            }else {
                str = new StringBuilder();
                while(i < s.length() && (c = s.charAt(i)) >= '0' && (c = s.charAt(i)) <= '9'){
                    str.append(c);
                    i++;
                }
                ls.add(str.toString());
            }
        }while (i < s.length());
        return ls;
    }

    public static List<String> parseSuffixExpressionList(List<String> ls){
        //符号栈
        Stack<String> s1 = new Stack<>();

        List<String> s2 = new ArrayList<>();
        for(String item : ls){
         if(item.matches("\\d+")){
             s2.add(item);
         }else if(item.equals("(")){
             s1.push(item);
         }else if(item.equals(")")){
             while(!s1.peek().equals("(")){
                 s2.add(s1.pop());
             }
             //将"("弹出栈
             s1.pop();
         }else {
             //栈顶运算符优先级大于等于此时运算符 s1运算符出栈并进入s2
             while(s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item)){
                s2.add(s1.pop());
             }
             s1.push(item);
         }
        }
        //将s1中剩余的运算符依次弹出并加入s2
        while(s1.size() != 0){
            s2.add(s1.pop());
        }
    return s2;
    }

    public static List<String> getListString(String suffixExpression){
        String[] split = suffixExpression.split(" ");
        List<String> list = new ArrayList<>();
        for(String ele : split){
            list.add(ele);
        }
        return list;
    }

    public static int calculate(List<String> ls){
        //只需要一个栈
        Stack<String> stack = new Stack<>();
        for(String item : ls){
            //匹配多位数
            if(item.matches("\\d+")){
                stack.push(item);
            }else{
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                int res = 0;
                if(item.equals("+")){
                    res = num1 + num2;
                }else if(item.equals("-")){
                    res = num1 - num2;
                }else if(item.equals("*")){
                    res = num1 * num2;
                }else if(item.equals("/")){
                    res = num1 / num2;
                }else {
                    throw new RuntimeException("运算符有误");
                }
                stack.push("" + res);
            }
        }
        return Integer.parseInt(stack.pop());
    }
}

class Operation{
    private static int ADD = 1;
    private static int SUB = 1;
    private static int MUL = 2;
    private static int DIV = 2;

    public static int getValue(String operation){
        int result = 0;
        switch (operation){
            case "+":
                result = ADD;
                break;
            case "-":
                result = SUB;
                break;
            case "*":
                result = MUL;
                break;
            case "/":
                result = DIV;
                break;
            case "(":
                result = 0;
                break;
            default:
                System.out.println("不存在该运算符");
                break;
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值