Postfix to Infix

人盡茶涼 提交于 2019-11-26 11:09:57

Infix expression: The expression of the form a op b. When an operator is in-between every pair of operands.
Postfix expression: The expression of the form a b op. When an operator is followed for every pair of operands.

Input : abc++
Output : (a + (b + c))

Input  : ab*c+
Output : ((a*b)+c)分析1. Read the next symbol from the input.2.If the symbol is an operand, push it onto the stack.3.Otherwise,…3.1 the symbol is an operator.…3.2 Pop the top 2 values from the stack.…3.3 Put the operator, with the values as arguments and form a string.…3.4 Push the resulted string back to stack.
 1 class Solution {
 2     boolean isOperator(char x) {
 3         switch (x) {
 4             case '+':
 5             case '-':
 6             case '/':
 7             case '*':
 8                 return true;
 9             default:
10                 return false;
11         }
12     }
13 
14     String postToInfix(String exp) {
15         Stack<String> s = new Stack<String>();
16 
17         for (int i = 0; i < exp.length(); i++) {
18             if (!isOperator(exp.charAt(i))) {
19                 s.push(exp.charAt(i) + "");
20             } else {
21                 String op1 = s.pop();
22                 String op2 = s.pop();
23                 s.push("(" + op2 + exp.charAt(i) + op1 + ")");
24             }
25         }
26         return s.peek();
27     }
28 }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!