[參考文獻:嚴蔚敏.數據結構(C語言版)]
表達式求值是程序設計語言編譯中的一個最基本問題,它的實現是棧應用的一個典型例子.
搞了一天,有相關的好的算法請大家傳上來,一起分享.
表3.1: 定義了算符之間的優先關系:
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) //根據表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("表達式錯誤");
else
f = "<";
break;
case ")":
switch (t1)
{
case "(": f = "="; break;
case "#": throw new ArgumentOutOfRangeException("表達式錯誤");
default: f = ">"; break;
}
break;
case "#":
switch (t1)
{
case "#": f = "="; break;
case "(": throw new ArgumentOutOfRangeException("表達式錯誤");
default: f = ">"; break;
}
break;
}
return f;
}
private static bool In(string c) //判斷c是否為運算符
{
switch(c)
{
case"+":
case"-":
case"*":
case"/":
case"(":
case")":
case"#": return true ;
default: return false ;
&n