Prefix to Infix Conversion

Infix : An expression is called the Infix expression if the operator appears in between the operands in the expression. Simply of the form (operand1 operator operand2).
Example : (A+B) * (C-D)

Prefix : An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 operand2).
Example : *+AB-CD (Infix : (A+B) * (C-D) )

Given a Prefix expression, convert it into a Infix expression.

analysis:

  • Read the Prefix expression in reverse order (from right to left)
  • If the symbol is an operand, then push it onto the Stack
  • If the symbol is an operator, then pop two operands from the Stack
  • Create a string by concatenating the two operands and the operator between them.
  • string = (operand1 + operator + operand2)
  • And push the resultant string back to Stack
  • Repeat the above steps until end of Prefix expression.
 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 preToInfix(String pre_exp) {
15         Stack<String> stack = new Stack<>();
16         int length = pre_exp.length();
17         for (int i = length - 1; i >= 0; i--) {
18             if (isOperator(pre_exp.charAt(i))) {
19                 String op1 = stack.pop();
20                 String op2 = stack.pop();
21 
22                 String temp = "(" + op1 + pre_exp.charAt(i) + op2 + ")";
23                 stack.push(temp);
24             } else {
25                 stack.push(pre_exp.charAt(i) + "");
26             }
27         }
28         return stack.peek();
29     } 
30 }

 

Guess you like

Origin www.cnblogs.com/beiyeqingteng/p/11318704.html
Recommended