标签:
后缀表达式求值算法
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!");
前缀表达式求值算法
算法一:从表达式尾部开始处理(从右至左)
伪代码描述:
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!");
中缀表达式转换为后缀表达式算法
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);}
标签:
原文地址:http://my.oschina.net/lucusguo/blog/506528