`

java中缀表达式转后缀表达式

 
阅读更多
算法思想数据结构的书上都有,网上也能搜到,只是贴一个示例代码
package info.lwjlaser.tree;

import java.util.Stack;

public class Postfix {
	public static void main(String [] args)
	{
		String expression = "(a+b)*(a-b)";
//		String expression = "a+b*c+(d*e+f)*g";
		deal(expression);
	}
	private static void deal(String ex)
	{
		Stack<Character> st = new Stack<Character>();
		char [] temps = ex.toCharArray();
		for(char temp : temps)
		{
			switch (temp)
			{
				case '+' :
				case '-' :
					while (!st.isEmpty() && st.peek()!='(')
					{
						System.out.print(st.pop());
					}
					st.push(temp);
					break;
				case '*' :
				case '/' :
					while (!st.isEmpty() && (st.peek() == '*' || st.peek() == '/'))
					{
						System.out.print(st.pop());
					}
					st.push(temp);
					break;
				case ')' :
					while (st.peek() != '(')
					{
						System.out.print(st.pop());
					}
					st.pop();
					break;
				case '(' :
					st.push('(');
					break;
				default :
					System.out.print(temp);
			}
		}
		while(!st.isEmpty())
		{
			System.out.print(st.pop());
		}
	}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics