使用栈的方式进行四则运算计算
//为清析思路,此函数从count_value函数里分离出来,这是正真计算中缀表达式的代码
//思路详解(详见刘志伟老师数据结构小课\Lab08\queuePractice)
void fun()
{
string temp;
while (!(str_stack.isEmpty()))
{
temp = str_stack.pop_front();
if (temp == "(")
{
oper_stack.push_back(temp);
}
else if (temp == ")")
{
temp = oper_stack.pop_back();
while (!(temp == "("))
{
try
{
count_oper(temp);
temp = oper_stack.pop_back();
}
catch (Exception myException)
{
throw myException;
}
}
}
else if (temp == " " || temp == "-" || temp == "*" || temp == "/")
{
if (!oper_stack.isEmpty() && oper_test(temp) < oper_test(oper_stack.peek_back()))
try
{
count_oper(oper_stack.pop_back());
}
catch (Exception myException)
{
throw myException;
}
oper_stack.push_back(temp);
}
else
num_stack.push_back(temp);
}
while (!oper_stack.isEmpty())
{
temp = oper_stack.pop_back();
try
{
count_oper(temp);
}
catch (Exception myException)
{
throw myException;
}
}
}
//表达式运算函数,用于将已入栈的中缀表达式进行数值运算,并返回结果
public string count_value()
{
cut();
try
{
fun();//运算函数
}
catch (Exception myException)
{
throw myException;
}
//Console.WriteLine(num_stack.pop_back());
return num_stack.pop_back();
}
string value; //存储参与运算表达式
Stack str_stack;//存储已分解的表达式
Stack num_stack;//参与运算时临时存储数字的栈
Stack oper_stack;//参与运算时临时存储运算符的栈
}
评论