逆波兰表达式与迷宫算法

中项表达式是人类的算术思路,逆波兰表达式是机器结合栈结构完成算式解析的最佳结构。

后缀表达式利用栈实现计算文章链接:https://zhuanlan.zhihu.com/p/357982040

迷宫算法
文章链接:https://blog.csdn.net/m0_53157173/article/details/114486303

将中项表达式转化为后缀表达式的实现(Java)

package algorithm;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Stack;

public class AfterTrans {
    private static void trans(String input){
        Stack<Character>mem=new Stack<>();
        HashMap<Character,Integer>priority=new HashMap<>();
        priority.put('*',2);
        priority.put('/',2);
        priority.put('+',1);
        priority.put('-',1);
        for(int i=0;i<input.length();++i){
            switch (input.charAt(i)){
                case '+':;
                case '-':while(!mem.isEmpty()&&!(((Character)'(').equals(mem.peek()))&&priority.get(input.charAt(i))<= priority.get(mem.peek())){
                    System.out.print(mem.pop());
                }
                mem.push(input.charAt(i));break;
                case '*':;
                case '/':
                    mem.push(input.charAt(i));break;
                case '(':mem.push(input.charAt(i));break;
                case ')':while(!(((Character)'(').equals(mem.peek()))){
                    System.out.print(mem.pop());
                }
                mem.pop();break;
                case ' ':break;
                default:
                    int temp=0;
                    while (i<input.length()&&(Character.isDigit(input.charAt(i)))){
                    temp=temp*10+(input.charAt(i)-'0');
                    ++i;
                }
                    --i;
                    System.out.print(temp);
            }
        }
        while(!mem.isEmpty()){
            System.out.print(mem.pop());
        }
    }
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        while(true) {
            System.out.println("请输入表达式:");
            String temp = sc.nextLine();
            trans(temp);
            System.out.println();
        }
    }

}

posted @ 2023-10-13 18:04  adamaik  阅读(20)  评论(0)    收藏  举报