中缀表达式转后缀表达式分为以下几个步骤:
1.若遇到数字或.,则直接输出;
2.若遇到(直接入栈;
3.若遇到运算符,则需将该运算符与栈顶运算符比较,若该运算符小于或等于栈顶运算符,则将栈顶运算符输出,并将该运算符压入栈(不管怎样);
4.若遇到),则将(前面的元素全部输出,并将(弹出;
5.循环上述四步。
代码实现
import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;
public class Test {
private static String[] houZhui(String middle)// 中缀表达式转后缀表达式
{
String last[] = new String[middle.length()+1];
StringBuffer number = new StringBuffer();// 用来保存数字
Stack
s = new Stack
();// 放运算符
String a;
s.push("#");// 起始符,栈底元素
int i = 0, j = 0;
char ch;
for (i = 0; i < middle.length();) {
ch = middle.charAt(i);
if (Character.isDigit(ch)){
while (Character.isDigit(ch))
{
number.append(ch);
if(i
1 && s.peek() != "(")
last[j++] = s.pop();
a = String.valueOf(ch);
s.push(a);
}
else if(ch=='*'||ch=='/'){
while (s.size() > 1 && (s.peek() == "*") || s.peek() == "/")
// 优先级比较,与栈顶比较
last[j++] = s.pop();
a = String.valueOf(ch);
s.push(a);
}
i++;
}
while (s.size() > 1)
last[j++] = s.pop();
last[j] = "#";
return last;
}
public static String Calculate(String middle)// 后缀表达式求值
{
String last[] = null;
try {
last = houZhui(middle);
} catch (EmptyStackException e) {
}
int i = 0;
int x1, x2, n;
String str;
Stack
s = new Stack
(); while (last[i] != "#") { str = last[i]; char ch=str.charAt(0); if(Character.isDigit(ch)){ s.push(str); } else if(ch== '+'){ x1 = Integer.parseInt(s.pop()); x2 = Integer.parseInt(s.pop()); n = x1 + x2; s.push(String.valueOf(n)); } else if(ch=='-'){ x1 =Integer.parseInt(s.pop()); x2 =Integer.parseInt(s.pop()); n = x2 - x1; s.push(String.valueOf(n)); } else if(ch=='*'){ x1 = Integer.parseInt(s.pop()); x2 = Integer.parseInt(s.pop()); n = x1 * x2; s.push(String.valueOf(n)); } else if(ch=='/'){ x1 =Integer.parseInt(s.pop()); x2 =Integer.parseInt(s.pop()); n = x2 / x1; s.push(String.valueOf(n)); } i++; } String result = s.pop(); return result; } public static void main(String args[]) { Scanner input=new Scanner(System.in); String str=input.next(); System.out.println(Calculate(str)); } }