首页 > 其他 > 详细

Postfix to Infix

时间:2019-08-08 09:09:37      阅读:94      评论:0      收藏:0      [点我收藏+]

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 }

 

Postfix to Infix

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

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