编译原理逆波兰式的实现(java)

博客介绍编译原理基本原理,利用栈的后进先出和运算符优先级表进行运算。判断多种情况,如非运算符直接输出、栈顶为左括号且来的非右括号则入栈等,最后遍历完表达式将栈内元素输出,还给出了相关代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本原理:

利用栈的后进先出以及运算符优先级表。

判断几个情况:

    1.如果不是运算符直接输出;

    2.栈顶是左括号,在来的字符不是右括号的情况下直接入栈;

    3.来的是右括号时,将栈内字符出栈病输出直到遇到左括号,左括号也出栈,但不入栈

    4.来的运算符优先级低于栈顶运算符时,将栈顶运算符出栈直到栈顶运算符优先级低于新来的运算符,然后新来的入栈

    5.最后,如果表达式遍历完了,将栈内所有元素输出

代码如下:

import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class nbl {
    public static void main(String[] args) throws IOException{
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(".//data.txt")));
        String[] priority0 = reader.readLine().split(" ");
        StringBuilder str = new StringBuilder();  //用来输出逆波兰式
        LinkedList<String> priority = new LinkedList<>(Arrays.asList(priority0));  //记录运算符优先级
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入表达式(符号之间请用空格隔开):");
        String[] equ = sc.nextLine().split(" ");  //使用字符串数组存放表达式
        sc.close();
        LinkedList<String> stack = new LinkedList<>();  //用来模拟栈
        for (String s : equ) {
            if (!priority.contains(s))
                str.append(s);
            else {
                if (stack.isEmpty() || stack.getLast().equals("(") || (priority.indexOf(s) > priority.indexOf(stack.getLast()) && !s.equals(")")))
                    stack.addLast(s);
                else if (s.equals(")")) {
                    while (!stack.getLast().equals("("))
                        str.append(stack.removeLast());
                    stack.removeLast();
                } else {
                    while (!stack.isEmpty() && (priority.indexOf(s) < priority.indexOf(stack.getLast())) && !stack.getLast().equals("(") && !stack.getLast().equals(")")) {
                        str.append(stack.removeLast());
                    }
                    stack.addLast(s);
                }
            }
        }
        while (!stack.isEmpty()) {
            str.append(stack.removeLast());
        }
        System.out.println("逆波兰式为:" + str.toString());
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值