Java将算术表达式由中序表达式转化为后序表达式

如题,使用Java将中序表达式转化为后序表达式


import java.util.Scanner;
import java.util.Stack;

public class Q100310 {
	private static void infixToPostfix(String exp)
	{
		String[] params=exp.split(" ");
		Stack<String> stack=new Stack<String>();
		for(int i=0;i<params.length;i++)
		{
			if(isOperator(params[i])) {stack.push(params[i]);}
			else if(params[i].equals("(")) continue;
			else if(params[i].equals(")")) System.out.print(stack.pop()+" ");
			else System.out.print(params[i]+" ");
		}
	}
	
	private static boolean isOperator(String s)
	{
		return(s.equals("+")||s.equals("-")||s.equals("/")||s.equals("*"));
	}
	
	public static void main(String[] args)
	{
		Scanner scanner=new Scanner(System.in);
		while(scanner.hasNext())
			infixToPostfix(scanner.nextLine());
		scanner.close();
	}

}

输入:

( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) ) )

输出:

1 2 + 3 4 - 5 6 - * * 

你可能感兴趣的:(Eclipse,JAVA基础)