将中缀表达式转换为前缀表达式
要通过计算机求解表达式,我们可以将它转换为后缀形式或前缀形式。在这里,我们将看到中缀表达式如何转换为前缀形式。
首先反转中缀表达式。注意,在反转时,开括号和闭括号也需要反转。
例如:表达式:A + B * (C - D)
反转表达式后为:) D – C ( * B + A
因此,我们需要将开括号转换为闭括号,反之亦然。
反转后,使用中缀到后缀算法将表达式转换为后缀形式。之后,再次反转后缀表达式以得到前缀表达式。
输入和输出
Input: Infix Expression: x^y/(5*z)+2 Output: Prefix Form Is: +/^xy*5z2
算法
infixToPrefix(infix)
输入 - 需要转换为前缀形式的中缀表达式。
输出 - 前缀表达式。
Begin reverse the infix expression for each character ch of reversed infix expression, do if ch = opening parenthesis, then convert ch to closing parenthesis else if ch = closing parenthesis, then convert ch to opening parenthesis done postfix := find transformed infix expression to postfix expression prefix := reverse recently calculated postfix form return prefix End
示例
#include<iostream> #include<stack> #include<locale> //for function isalnum() #include<algorithm> using namespace std; int preced(char ch) { if(ch == '+' || ch == '-') { return 1; //Precedence of + or - is 1 }else if(ch == '*' || ch == '/') { return 2; //Precedence of * or / is 2 }else if(ch == '^') { return 3; //Precedence of ^ is 3 }else { return 0; } } string inToPost(string infix) { stack<char> stk; stk.push('#'); //add some extra character to avoid underflow string postfix = ""; //initially the postfix string is empty string::iterator it; for(it = infix.begin(); it!=infix.end(); it++) { if(isalnum(char(*it))) postfix += *it; //add to postfix when character is letter or number else if(*it == '(') stk.push('('); else if(*it == '^') stk.push('^'); else if(*it == ')') { while(stk.top() != '#' && stk.top() != '(') { postfix += stk.top(); //store and pop until ( has found stk.pop(); } stk.pop(); //remove the '(' from stack }else { if(preced(*it) > preced(stk.top())) stk.push(*it); //push if precedence is high else { while(stk.top() != '#' && preced(*it) <= preced(stk.top())) { postfix += stk.top(); //store and pop until higher precedence is found stk.pop(); } stk.push(*it); } } } while(stk.top() != '#') { postfix += stk.top(); //store and pop until stack is not empty stk.pop(); } return postfix; } string inToPre(string infix) { string prefix; reverse(infix.begin(), infix.end()); //reverse the infix expression string::iterator it; for(it = infix.begin(); it != infix.end(); it++) { //reverse the parenthesis after reverse if(*it == '(') *it = ')'; else if(*it == ')') *it = '('; } prefix = inToPost(infix); //convert new reversed infix to postfix form. reverse(prefix.begin(), prefix.end()); //again reverse the result to get final prefix form return prefix; } int main() { string infix = "x^y/(5*z)+2"; cout << "Prefix Form Is: " << inToPre(infix) << endl; }
输出
Prefix Form Is: +/^xy*5z2
广告