Implementation process:
1. Create two empty arrays first, result is used to store the results, and temp is used to store the symbols; then create a symbol set OPS store +-*/symbol
2. Go to the expression character array, start traversing the array
3. If an operator is encountered, push directly into the result array
4. Encountering parentheses
1) Encounter ' (', push into staging area
2) ') ', pops up the staging area stack top operator until ' (', and removes staging area ' ('
5. Operator encountered
1) If staging area
① is empty
② Staging Area stack top for ' ('
③ the current symbol has precedence over the staging area stack top operator
These situations are pushed directly into the stack
2) Otherwise, eject the top operator of the staging area and push it into the result area again, step 5
6. When the traversal is complete, the staging area remaining operators are popped and pushed into the result area.
functionRP (str) {vararr = str.split (' '); varOPS = ' +-#*/'. Split ('); #用来分级, +-is the same level, */same level, the position difference between level two is at least 2varresult = [], temp = []; Arr.foreach (function(Ele, Ind) {if(Ele = = ' ('{Temp.push (ele);//left parenthesis push directly into staging area}Else if(Ele = = ') ') { varFlag =true; while(flag) {if(temp[temp.length-1]! = ' (') {Result.push (Temp.pop ())}Else{temp.pop (); Flag=false; } } } Else if(Ops.indexof (ele)! =-1) {CB (Ele, temp)functionCB (x, O) {if(O.length = = 0 | | o[o.length-1] = = ' (' | |ops.indexof (x)-Ops.indexof (O[o.length-1]) > 2) {//Judge rating O.push (x)}Else{Result.push (O.pop ()); returnCB (x, O)}} } Else{Result.push (ele); } }) while(Temp.length > 0) { if(temp[temp.length-1]! = ' (') {Result.push (Temp.pop ())}Else{Temp.pop ()}}returnResult.join (' ');}
The implementation of the procedure is to refer to a Java write implementation process, but again to find the article has not found, find and then fill up.
JavaScript infix expression to inverse Polish style (arithmetic)