(一)前缀,中缀,后缀表达式
1.中缀表达式:Hdu 1237
http://acm.hdu.edu.cn/showproblem.php?pid=1237
对于表达式1 + 2 / 3 * 4 + 5
主要思想是在表达式末尾加入”#”,在运算符栈中加”#”作为标志。
----表达式 ---operand ---number
1 + 2 / 3 * 4 + 5 # #
i = 1 # 1
I = 2 # + 1
I = 3 # + 1 ,2
I = 4 # + / 1 ,2
I = 5 # + / 1 ,2 ,3
I = 6 # + 1, 2/3
# + *
I = 7 # + * 1, 2/3, 4
I = 8 # + 1, 2/3*4,
# + + 1, 2/3*4
I = 9 # + + 1, 2/3*4, 5
I = 10 # + 1, 2/3*4+5
# 2/3*4 + 5 + 1
参照网上代码写的:
http://www.cnblogs.com/robotcator/p/3420244.html
3.调度场算法/中序转逆序(非完整版)
1:依次读取输入。
2:如果是左括号,则入栈;如果是操作数则进入后缀表达式表。
3:如果是右括号,则将栈中的符号放入后缀表达式表中,直到遇到左括号
4:如果是操作符且大于栈顶的操作符则入栈,如果小于等于栈顶的操作符,则将栈中元素放入后缀表达式表中,直到遇到栈顶元素大于当前且将将当前运算符压入栈中。
5:重复操作直到输入为空
(如何在word中实现代码高亮:http://www.7mdm.com/801.html)
void prifix_postfix(char *data, char *suffix)
{
stack<char> s;
int k = 0;
for(int i = 0; i < (int)strlen(data); i ++)
{
// if it is a digit.
if(data[i] >= '0' && data[i] <= '9'){
while(data[i] >= '0' && data[i] <= '9'){
suffix[k++] = data[i];
i ++;
}
suffix[k++] = ' ';
i --;
//attention, keep the current position
}
else{
switch(data[i]){
case '(': s.push(data[i]); break;
case ')': {
char c = s.top();
s.pop();
while(c != '('){
suffix[k++] = c;
suffix[k++] = ' ';
c = s.top();
s.pop();
}
break;
}
// if it's ')', the stack element move to suffix until the '('
default:{
if(s.empty()) s.push(data[i]);
else{
if(priority(s.top()) < priority(data[i]))
s.push(data[i]);
// if the moment operand less than the stack operand
else {
while(!s.empty() &&
(priority(s.top()) >= priority(data[i]))){
suffix[k++] = s.top();
suffix[k++] = ' ';
s.pop();
}
s.push(data[i]);
//pop the operand of stack and push the current operand to the stack
}
}
break;
}// end default
}// end els
}// end else
}//end for
while(!s.empty()){
suffix[k++] = s.top();
suffix[k++] = ' ';
s.pop();
}
suffix[k] = '\0'; // remove the extra blank!!!
for(int i = 0; i < k; i ++)
cout << suffix[i] ;
cout << endl;
}
double operate(double temp1, double temp2, char op)
{
switch(op)
{
case '+': return temp1+temp2;
case '-': return temp1-temp2;
case '*': return temp1*temp2;
case '/': return temp1/temp2;
}
}
double calculate(char *suffix)
{
stack<double> s;
for(int i = 0; i < (int)strlen(suffix); i ++)
{
if(suffix[i] == ' ') continue;
else if(suffix[i] >= '0' && suffix[i] <= '9'){
double temp = 0;
while(suffix[i] != ' '){
temp = temp*10 + suffix[i]-'0';
i ++;
}
s.push(temp);
}
else{
double temp1 = s.top(); s.pop();
double temp2 = s.top(); s.pop();
temp1 = operate(temp2, temp1, suffix[i]);
s.push(temp1);
}
}
return s.top();
}
//prefix_postfix函数是中缀转后缀表达式,calculate是计算后缀表达式值得函数。

浙公网安备 33010602011771号