栈的应用——计算器中缀表达式转后缀表达式

栈的应用——计算器中缀表达式转后缀表达式

栈的应用——计算器中缀表达式转后缀表达式

栈的应用——计算器中缀表达式转后缀表达式 

栈的应用——计算器中缀表达式转后缀表达式

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class ExpressionTransfer {
	public static StringBuffer toPostFix(String infix){
		Stack<String> stack = new Stack<String>();
		
		StringBuffer postfix = new StringBuffer(infix.length()*2);
		
		int i = 0;
		while(i<infix.length()){
			char ch = infix.charAt(i);
			switch(ch){
			case '+':case '-':
				while(!stack.isEmpty() && !stack.peek().equals("(")){
					postfix.append(stack.pop());
				}
				stack.push(ch+"");
				i++;
				break;
			case '*':case '/':
				while(!stack.isEmpty() && stack.peek().equals("*") || stack.peek().equals("/")){
					postfix.append(stack.pop());
				}
				stack.push(ch+"");
				i++;
				break;
			case '(':
				stack.push("(");
				i++;
				break;
			case ')':
				String out = stack.pop();
				while(out != null && !out.equals("(")){
					postfix.append(out);
					out = stack.pop();
				}
				i++;
				break;
			default:
				while(i<infix.length() &&  ch>='0' && ch<='9'){
					postfix.append(ch);
					i++;
					if(i<infix.length()){
						ch = infix.charAt(i);
					}
				}
				postfix.append(" ");
			}
		}
		while(!stack.isEmpty()){
			postfix.append(stack.pop());
		}
		return postfix;
	}
	
	public static int toValue(StringBuffer postfix){
		//设置一个操作数栈
		Stack<Integer> stack = new Stack<Integer>();
		int value = 0;
		for(int i = 0;i<postfix.length();i++){
			char ch = postfix.charAt(i);
			if(ch >= '0' && ch<= '9'){
				value = 0;
				while(ch != ' '){
					value = value * 10 + Integer.parseInt(""+ch);
					ch = postfix.charAt(++i);
				}
				stack.push(value);
			}
			
			
			
			if(!(ch >= '0' && ch<= '9')){
				if(ch != ' '){
					int y = stack.pop();
					int x = stack.pop();
					
					switch(ch){
					case '+': value = x+y; break;
					case '-': value = x-y; break;
					case '*': value = x*y; break;
					case '/': value = x/y;break;
					}
					//显示运算过程
					System.out.println(x+(ch+"")+y+"="+value+", ");
					stack.push(value);
				}
			}
		}
		return stack.pop();
	}
	
	public static void main(String[] args){
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		try{
			String infix = br.readLine();
			StringBuffer postfix = toPostFix(infix);
			System.out.println("后缀表达式为: "+postfix);
			int result = toValue(postfix);
			System.out.println(result);
		}catch(IOException e){
			e.printStackTrace();
		}
		
	}
}

测试结果:

123+10*(45-50+20)/((35-25)*2+10)-11
后缀表达式为: 123 10 45 50 -20 +*35 25 -2 *10 +/+11 -
45-50=-5, 
-5+20=15, 
10*15=150, 
35-25=10, 
10*2=20, 
20+10=30, 
150/30=5, 
123+5=128, 
128-11=117, 
117

啦啦~啦啦啦~~~