[References: Yan Weimin. Data Structure (c)]
Expression evaluation is a basic problem in programming language compilation. Its implementation is a typical example of stack applications.
After one day, we have a good algorithm to share with you.
Table 3.1 defines the priority relationship between operators:
Using System;
Using System. Collections;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Text. RegularExpressions;
Namespace EvaluateExpression
{
Class EvaluateExpression
{
Private static string Precede (string t1, string t2) // the priority of the two symbols is determined based on table 3.1.
{
String f = string. Empty;
Switch (t2)
{
Case "+ ":
Case "-":
If (t1 = "(" | t1 = "#")
F = "<";
Else
F = "> ";
Break;
Case "*":
Case "/":
If (t1 = "*" | t1 = "/" | t1 = ")")
F = "> ";
Else
F = "<";
Break;
Case "(":
If (t1 = ")")
Throw new ArgumentOutOfRangeException ("expression error ");
Else
F = "<";
Break;
Case ")":
Switch (t1)
{
Case "(": f = "="; break;
Case "#": throw new ArgumentOutOfRangeException ("expression error ");
Default: f = ">"; break;
}
Break;
Case "#":
Switch (t1)
{
Case "#": f = "="; break;
Case "(": throw new ArgumentOutOfRangeException ("expression error ");
Default: f = ">"; break;
}
Break;
}
Return f;
}
Private static bool In (string c) // determines whether c is an operator
{
Switch (c)
{
Case "+ ":
Case "-":
Case "*":
Case "/":
Case "(":
Case ")":
Case "#": return true;
Default: return false;
& N