首页 > 其他 > 详细

Prefix to Infix Conversion

时间:2019-08-08 00:47:32      阅读:106      评论:0      收藏:0      [点我收藏+]

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.

分析:

  • 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 }

 

Prefix to Infix Conversion

原文:https://www.cnblogs.com/beiyeqingteng/p/11318704.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!