前面一章已经将前缀,中缀,后缀表达式的基本概念进行了介绍,同时也介绍了编程中较常用的中缀表达式转换到后缀和前缀表达式的方法。接下来主要针对前缀,中缀和后缀表达式求值来进行相应的讨论。
在上一篇BLOG中的开始就阐述了中缀表达式求值的过程,中缀表达式求值比较符合人脑的计算方式,而对于计算机来说并不是十分高效,需要多次对表达式进行遍历。下面贴出我自己实现的直接对中缀表达式按人脑计算方式进行求值的代码。
int lastIndex)
{
//外层如果是括号则去掉
if (exp[firstIndex] == '(' && exp[lastIndex] == ')')
{
return Evaluate(exp, firstIndex + 1, lastIndex - 1);
}
//进行计算
int position = 0;
char result = AddOrSub(exp, firstIndex, lastIndex, ref position);
if (result != '#')
{
//计算
if (result == '+')
{
return Evaluate(exp, firstIndex, position - 1) + Evaluate(exp, position + 1, lastIndex);
}
if (result == '-')
{
return Evaluate(exp, firstIndex, position - 1) - Evaluate(exp, position + 1, lastIndex);
}
}
result = MultiplyOrDevide(exp, firstIndex, lastIndex, ref position);
if (result != '#')
{
//计算
if (result == '*')
{
return Evaluate(exp, firstIndex, position - 1) * Evaluate(exp, position + 1, lastIndex);
}
if (result == '/')
{
return Evaluate(exp, firstIndex, position - 1) / Evaluate(exp, position + 1, lastIndex);
}
}
//生成实际数字值
if (exp[firstIndex] > '9' || exp[firstIndex] < '0')
Console.WriteLine("Error");
return RealNum(exp[firstIndex]);
}
public static char AddOrSub(char[] exp, int firstIndex, int lastIndex, ref int position)
{
System.Collections.Stack objStack = new Stack();
//找到返回操作符,找不到返回#
for (int i = firstIndex; i <= lastIndex; i++)
{
if (exp[i] == '(')
{
objStack.Push('(');
}
if (exp[i] == ')')
{
objStack.Pop();
}
if (exp[i] == '+' && objStack.Count == 0)
{
position = i;
return '+';
}
if (exp[i] == '-' && objStack.Count == 0)
{
position = i;
return '-';
}
}
//没有找到对应的操作符
return '#';
}
public static char MultiplyOrDevide(char[] exp, int firstIndex, int lastIndex, ref int position)
{
//找到返回操作符,找不到返回#
System.Collections.Stack objStack = new Stack();
//找到返回操作符,找不到返回#
for (int i = firstIndex; i <= lastIndex; i++)
{
if (exp[i] == '(')
{
objStack.Push('(');
}
if (exp[i] == ')')
{
objStack.Pop();
}
if (exp[i] == '*' && objStack.Count == 0)
{
position = i;
return '*';
}
if (exp[i] == '/' && objStack.Count == 0)
{
position = i;
return '/';
}
}
//没有找到对应的操作符
return '#';
}
public static int RealNum(char num)
{
return 0 + (num - '0');
}