1.3.10
编写一个过滤器InfixToPostfix,将算术表达式由中序表达式转为后序表达式。
其实很无聊的题目,但是它还不一定很快想到,因为有些反直觉,平时咱们从来都不搞什么后序表达式,又叫逆波兰表示法,波兰一位数学家发明,在咱们大中华没怎么见过有用的。
因为有些无聊,干脆直接上代码了:
public class E10310 {
public static void infixToPostfix(String str){
if (str == null){throw new NoSuchElementException("");}
String s = str.replaceAll("\s*", "");
String[] split = s.split("");
Stack<String>stack = new Stack<>();
//对表达式进行遍历
for (String arr : split){
if ("(".equals(arr)){
continue;
}else if (check(arr)){
stack.push(arr);
}else if (")".equals(arr)&&!stack.isEmpty()){
System.out.print(stack.pop()+" ");
}else {
System.out.print(arr+ " ");
}
}
}
private static boolean check(String str){
return "+".equals(str)|| "-".equals(str)||
"*".equals(str)|| "/".equals(str);
}
public static void main(String[]args){
String str = "( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) ) )";
infixToPostfix(str);
}
1.3.11
编写一段程序EvaluatePostfix,从标准输入中得到一个后序表达式,求值并打印结果(将上一题的程序中得到的输出用管道传递给这一段程序可以得到和Evaluate相同的行为).
每次读取到操作符的时候,将栈内元素弹出进行运算后压栈,到最后剩下的值就是结果,没什么可说的。上代码:
public class E10311
{
private static int evaluatePostfix(String s)
{
String[] params = s.split(" ");
Stack<Integer> stack = new Stack<Integer>();
for (String param : params) {
if ("+".equals(param)) {
int d2 = stack.pop();
int d1 = stack.pop();
stack.push(d1 + d2);
} else if ("-".equals(param)) {
int d2 = stack.pop();
int d1 = stack.pop();
stack.push(d1 - d2);
} else if ("*".equals(param)) {
int d2 = stack.pop();
int d1 = stack.pop();
stack.push(d1 * d2);
} else if ("/".equals(param)) {
int d2 = stack.pop();
int d1 = stack.pop();
stack.push(d1 / d2);
} else { // number
stack.push(Integer.parseInt(param));
}
}
return stack.pop();
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
System.out.println(evaluatePostfix(scanner.nextLine()));
}
scanner.close();
//或者直接用字符串测试就行String str = "1 2 + 3 4 - 5 6 - * * "
}