後綴表達式求值算法算法
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(); else printf("Suffix expression is invalid!");
前綴表達式求值算法express
算法一:從表達式尾部開始處理(從右至左)spa
僞代碼描述:code
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(); } else printf("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(); else printf("Prefix expression is invalid!");
中綴表達式轉換爲後綴表達式算法io
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); }
中綴表達式轉換爲前綴表達式算法class
從表達式尾部開始處理top
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);}