When infix expression is converted to suffix expression, what if the form of the original infix expression is (a + b * c) and the result is incorrect

CSDN Q & A 2021-12-30 11:07:46 阅读数:642

infix expression converted suffix expression

In the process of learning infix expression to suffix expression , I found that if a string is (a+bc) In the form of , Then the final result will be (a+b)c, What should I do ?, for example "1+(2+34)-5" This expression , The final calculation is 21, The program starts with the bracketed + Added to the stack , Without taking into account the subsequent multiplication sign , Obviously, the result is similar to "1+(43+2)-5" Is different , If you want to achieve results, you have to give 34 Add a pair of parentheses , become 1+(2+(34))-5 So what do we do ?
I compared the code in the book with that in the video The following code should be ok But you can't calculate a specific string What do I do ?
My original code is as follows :

```javapublic static List<String> toPostfixList(List<String> list){ Stack<String> stack = new Stack<String>(); List<String> stack2 = new ArrayList<String>(); for(String item:list) { if(item.matches("\\d+")) { stack2.add(item); }else if(item.equals("(")) stack.push(item); else if(item.equals(")")) { while(!stack.empty()&&!stack.peek().equals("(")) { stack2.add(stack.pop()); / } stack.pop(); } else { while(stack.size()!=0 && Operation.getPriority(stack.peek()) >= Operation.getPriority(item)) stack2.add(stack.pop()); stack.push(item); } } while(stack.size()!=0) stack2.add(stack.pop()); return stack2; }


Refer to the answer 1:

You can judge the priority of symbols ,
1. Such as now stack There is... In it + - Number , Then traverse to * / When , Then press stack, Last * / First out
2. If it is + - , Traversing + - , So it's the same as the top priority , Stack top first out , Then press stack

Refer to the answer 2:
版权声明:本文为[CSDN Q & A]所创,转载请带上原文链接,感谢。 https://primo.wiki/2021/12/202112301107433159.html