表达式求值及转换算法
生活随笔
收集整理的這篇文章主要介紹了
表达式求值及转换算法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
后綴表達式求值算法
stack?operands;??//運算數棧 while(沒到表達式尾) {scanf("一個運算對象op");if(op?is?運算數)operands.push(op);else?if(op?is?運算符){operand_right?=?operands.pop();operand_left?=?operands.pop();result?=?operand_left?op?operand_right;operands.push(result);}else{printf("Suffix?expression?is?invalid?!");} } if(operands.size()?==?1)return?operands.top(); elseprintf("Suffix?expression?is?invalid!");前綴表達式求值算法
算法一:從表達式尾部開始處理(從右至左)
偽代碼描述:
stack?operands;???//運算數棧 while(沒到達表達式首) {scanf("一個運算對象op");if(op?is?Operand)operands.push(op);else?if(op?is?Operator){operand_left?=?operands.pop();operand_right?=?operands.pop();result?=?operand_left?op?operand_right;operands.push(result);}else{printf("Prefix?expression?is?invalid!");} } if(operands.size()?==?1) {return?operands.top(); } elseprintf("Prefix?expression?is?invalid!");算法二:從表達式首部開始處理(從左至右)
stack?operations;??//運算對象棧,元素既可以是云算法,也可以是運算數 while(沒到表達式尾) {scanf("一個運算對象op");if(op?is?Operator){operations.push(op);}else?if(op?is?Operand){if(operations.top()?is?Operator){operations.push(op);}else{while(operations.top()?is?Operand){operand_right?=?op;operand_left?=?operations.pop();operator?=?operations.pop();op?=?operand_left?operator?operand_right;}operations.push(op);}}else{printf("Prefix?expression?is?invalid!");} } if(operations.size()?==?1)return?operations.top(); elseprintf("Prefix?expression?is?invalid!");中綴表達式轉換為后綴表達式算法
stack?operators;???//運算符棧 while(沒到表達式尾) {scanf("一個運算對象op");if(op?is?Operand){printf(op);}else?if(op?is?Operator){if(op?優先級大于?operator.top()?&&?op?is?not?右括號)operator.push(op);else?if(op?is?右括號){do{tmp?=?operators.pop();if(tmp?is?not?對應左括號){printf(tmp);}else{break;}if(operators.empty()){printf("Infix?expression?is?invalid!");}}while(1);}else{do{tmp?=?operators.pop();printf(tmp);}while(op?優先級小于?operators.top());operators.push(op);}}else{printf("Infix?expression?is?invalid!");} } while(!operators.empty()) {tmp?=?operators.pop();printf(tmp); }中綴表達式轉換為前綴表達式算法
從表達式尾部開始處理
stack?operators;??//運算符棧stack?operations;??//運算對象棧,元素既可以是運算符,也可以是運算數while?(沒到表達式首){scanf("一個運算對象op");if?(op?is?Operand){operations.push(op);}else?if?(op?is?Operator){if?(op?優先級大于?operators.top()?&&?op?is?not?左括號)operators.push(op);else?if?(op?is?左括號){do{tmp?=?operators.pop();if?(tmp?is?not?對應右括號){operations.push(tmp);}else{break;}if?(operators.empty()){printf("Infix?expression?is?invalid!");}}while(1);}else{do{tmp?=?operators.pop();operations.push(tmp);}while(op?優先級小于?operators.top());operators.push(op);}}else{printf("Infix?expression?is?invalid!");}}while(!operators.empty()){tmp?=?operators.pop();operations.push(tmp);}while(!operations.empty()){tmp?=?operations.pop();printf(tmp);}轉載于:https://my.oschina.net/lucusguo/blog/506528
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的表达式求值及转换算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到不认识的人死去了意味着什么
- 下一篇: 梦到给死去的亲人上坟是什么意思