Stack application _ expression evaluate _ C # implementation

Source: Internet
Author: User

[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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.