利用后缀表达式计算表达式

思路:

1.将中缀表达式转换为list

2.将中缀表达式的list转换为后缀表达式list

3.通过后缀表达式计算结果:思路见注释(详细) 

package stack;

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

public class PolandNotation
{
	public static void main(String[] args)
	{
		String exception = "1+((2+3)*4)-5";
		System.out.println("表达式 : " + exception);
		List<String> infixExpressionList = toInfixExpression(exception);
		System.out.println("中缀表达式对应的List :" + infixExpressionList);
		List<String> sufixExpressionList = parseSuffixExpression(infixExpressionList);
		System.out.println("后缀表达式对应的List :" + sufixExpressionList);
		
		int res = calculate(sufixExpressionList);
		System.out.println("计算结果 : " + res);
		
	}
	
	//将中缀表达式转成对应的list
	public static List<String> toInfixExpression(String s)
	{
		List<String> list = new ArrayList<>();
		int i = 0; //指针
		char c;   //指针时的字符串
		String str; //多位数的拼接
		do {
			//如果是一个非负,则直接进入list
			if((c=s.charAt(i)) < 48 || (c=s.charAt(i)) > 57)
			{
				list.add("" + c);
				i++; //后移
			}
			else 
			{
				str = "";
				while(i < s.length() && (c=s.charAt(i)) >= 48 && (c=s.charAt(i)) <= 57)
				{
					str = str + c; //多位数的话,进行拼接
					i++;
				}
				list.add(str);
			}
		}while(i < s.length());
		return list;
	}
	
	//将得到的中缀表达式对应的List => 后缀表达式的List
	public static List<String> parseSuffixExpression(List<String> list)
	{
		//定义两个栈
		Stack<String> s1 = new Stack<>();//符号栈
		//说明:因为S2这个栈,在整个转换过程中,没有pop操作,而且后面需要我们逆序输出
		//因此比较麻烦,这里我们就不用Stack<String>,直接使用List<String>S2
		List<String> s2 = new ArrayList<>();  //存储中间结果的List2
		
		//遍历List
		for(String item : list)
		{
			//如果是一个数,加入s2
			if(item.matches("\\d+"))
			{
				s2.add(item);
			}
			else if(item.equals("("))
			{
				s1.push(item);
			}
			else if(item.equals(")"))
			{
				//如果是右括号,则一次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
				while(!s1.peek().equals("("))
				{
					s2.add(s1.pop());
				}
				s1.pop();  //弹出左括号
			}
			else
			{
				//当item的优先级小于等于s1的栈顶运算符,将s1的栈顶的运算符弹出并加入s2中,再次转到(4.1)与s1中新的运算符相比较
				while(s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item))
				{
					s2.add(s1.pop());
				}
				s1.push(item);
			}
		}
		while(s1.size() != 0)
		{
			s2.add(s1.pop());
		}
		return s2;
	}
	
	//将一个逆波兰表达式,依次将数据和运算符放入到ArrayList中
	public static List<String>getListString(String suffixException)
	{
		//将suffixException分割
		String[] split = suffixException.split(" ");
		List<String>list = new ArrayList<String>();
		for(String item : split)
		{
			list.add(item);
		}
		return list;
	}
	
	//计算逆波兰表达式
	/*
	 * 1)从左至右扫描,将3、4压入栈中
	 * 2)遇到+运算符,因此弹出4和3。计算3+4的值,然后将7入栈
	 * 3)将5入栈
	 * 4)遇到*运算符,从栈中弹出两个数,7、5,计算5*7,将值35压入栈中
	 * 5)6入栈
	 * 7)最后遇到-号运算符,计算35-6,得到29;
	 */
	
	public static int calculate(List<String>ls)
	{
		//创建栈
		Stack<String> stack = new Stack<String>();
		//遍历ls
		for(String item : ls)
		{
			//这里使用正则表达式来进行取值
			if(item.matches("\\d+"))  //匹配的是多位数
			{
				stack.push(item);
			}
			else
			{
				int num1 = Integer.parseInt(stack.pop());
				int num2 = Integer.parseInt(stack.pop());
				int res = 0;
				if(item.equals("+"))
				{
					res = num2 + num1;
				}
				else if(item.equals("-"))
				{
					res = num2 - num1;
				}
				else if(item.equals("*"))
				{
					res = num2 * num1;
				}
				else if(item.equals("/"))
				{
					res = num2 / num1;
				}
				else
					throw new RuntimeException("运算符异常");
				
				
				//结果入栈
				stack.push("" + res);
			}
		}
		
		//最后留在stack里面的最后一个元素就是结果
		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;
			default:
				System.out.println("转后缀表达式时,运算符异常");
				break;
		}
		return result;
	}
}

计算结果:

发布了246 篇原创文章 · 获赞 22 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/gjs935219/article/details/104782386
今日推荐