我写的顺序栈表达式求值的代码,但运行的时候不能正确运算,有哪位大大看看哪里不对,一下是代码:
//用顺序栈实现算法
public bool MatchBracket(char[] charlist)
{
SeqStack<char> s = new SeqStack<char>(50);
int len = charlist.Length;
for (int i = 0; i < len; ++i)
{
if (s.IsEmpty())
{
s.Push(charlist[i]);
}
else if (((s.GetTop() == '(') && (charlist[i] == ')')) || (s.GetTop() == '[' && charlist[i] == ']'))
{
s.Pop();
}
else
{
s.Push(charlist[i]);
}
}
if (s.IsEmpty())
{
return true;
}
else
{
return false;
}
}
public static int EvaluateExpression(String calc)
{
SeqStack<char> optr = new SeqStack<char>(20);
SeqStack<int> opnd = new SeqStack<int>(20);
calc = calc + "#";
optr.Push('#');
Char c = '0';
char theta = '0';
int a = 0;
int b = 0;
Char[] ca = calc.ToCharArray();
int index = 0;
while (c != '#')
{
c = ca[index++];
if ((c != '+') && (c != '-') && (c != '*') && (c != '/') && (c != '(') && (c != ')')&&(c!='#'))
{
int h = int.Parse(c.ToString());
opnd.Push(h);
}
else
{
switch (Precede(optr.GetTop(), c))
{
//如果栈顶操作符优先级高,返回>
//如果栈顶操作符优先级低,返回<
case '<':
optr.Push(c);
//c = Convert.ToChar(Console.Read());
break;
case '=':
optr.Pop();
//c = Convert.ToChar(Console.Read());
break;
case '>':
//将操作符从optr栈中取出
theta = optr.GetTop();
//取出两个操作数
b = opnd.Pop();
a = opnd.Pop();
//将计算结果存入open栈
opnd.Push(Operate(a, theta, b));
break;
case 'e':
Console.WriteLine("无效的算术表达式");
break;
} //end of switch
}//end of else
}//end of while
return opnd.GetTop();
}
public static char Precede(char a, char b)
{
if (a == '+' || a == '-')
{
if (b == '+' || b == '-' || b == ')' || b == '#')
return '>';
else
return '<';
}
if (a == '*' || a == '/')
{
if (b == '(')
return '<';
else
return '>';
}
if (a == '(')
{
if (b == ')')
return '=';
if (b == '#')
return 'e';
else
return '<';
}
if (a == ')')
{
if (b == '(')
return 'e';
else
return '>';
}
else //(a == '#')
{
if (b == ')')
return 'e';
if (b == '#')
return '=';
else
return '<';
}
}
public static int Operate(int a, char b, int c)
{
int d = 0;
switch (b)
{
case '*':
d = a * c;
break;
case '+':
d = a + c;
break;
case '-':
d = a - c;
break;
case '/':
d = a / c;
break;
}
return d;
}