看大话数据结构 利用栈实现四则运算这一块儿正好是只有讲解没有代码实现的 于是照着书上的原理自己写了个四则运算的C#代码 以后可以考虑到作为自己的类库中的组件
主要涉及的是逆波兰式 程序主要部分为逆波兰式的产生 以及通过逆波兰式产生最终的四则运算结果
使用的时候只需输入四则运算的算是即可 如2*(1+2)+3*(4+5) 没有中括号大括号 程序会分三个步骤来 首先分割算式 将运算符与数字之间插入空格 方便之后的出入栈操作 如
2 * ( 1 + 2 ) + 3 * ( 4 + 5 )
之后将原式子转变为逆波兰式 最后通过逆波兰式生成最终的算术结果
-
-
using System.Collections.Generic;
-
-
using System.Text.RegularExpressions;
-
-
namespace ConsoleApplication1
-
-
-
-
private static Dictionary<string, int> _operatorLevel;
-
-
public static void Main(string[] arg)
-
-
Console.WriteLine("Type in the source expr");
-
string sourceExpression = Console.ReadLine();
-
Console.WriteLine(InsertBlank(sourceExpression));
-
string rpnExperssion = ConvertToRPN(InsertBlank(sourceExpression));
-
Console.WriteLine(rpnExperssion);
-
Console.WriteLine(GetResult(rpnExperssion));
-
-
-
-
public static double GetValue(double left, double right, char _operator)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
public static double GetResult(string source)
-
-
Stack<string> stack = new Stack<string>();
-
var list = source.Split(' ');
-
for (int i = 0; i < list.Length; i++)
-
-
string current = list[i];
-
if (Regex.IsMatch(current, "^([0-9]{1,}){1}quot;))
-
-
-
-
else if (OperatorLevel.ContainsKey(current))
-
-
double right = double.Parse(stack.Pop());
-
double left = double.Parse(stack.Pop());
-
stack.Push(GetValue(left, right, current[0]).ToString());
-
-
-
return double.Parse(stack.Pop());
-
-
-
public static string ConvertToRPN(string source)
-
-
StringBuilder result = new StringBuilder();
-
Stack<string> stack = new Stack<string>();
-
string[] list = source.Split(' ');
-
for (int i = 0; i < list.Length ; i++)
-
-
string current = list[i];
-
if (Regex.IsMatch(current, "^([0-9]{1,}){1}quot;))
-
-
result.Append(current + " ");
-
-
else if (OperatorLevel.ContainsKey(current))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
while (stack.Count > 0 && stack.Peek() != "(")
-
-
result.Append(stack.Pop() + " ");
-
-
-
-
-
-
if (OperatorLevel[current] < OperatorLevel[prev])
-
-
-
-
-
-
-
-
result.Append(top + " ");
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
if (top != "(" && top != ")")
-
-
result.Append(top + " ");
-
-
-
-
return result.ToString();
-
-
-
public static string InsertBlank(string source)
-
-
StringBuilder sb = new StringBuilder();
-
var list = source.ToCharArray();
-
foreach (var temp in list)
-
-
if (OperatorLevel.ContainsKey(temp.ToString()))
-
-
-
sb.Append(temp.ToString());
-
-
-
-
-
-
-
-
-
-
-
-
public static Dictionary<string, int> OperatorLevel
-
-
-
-
-
-
_operatorLevel = new Dictionary<string, int>();
-
_operatorLevel.Add("+", 0);
-
_operatorLevel.Add("-", 0);
-
_operatorLevel.Add("(", 1);
-
_operatorLevel.Add("*", 1);
-
_operatorLevel.Add("/", 1);
-
_operatorLevel.Add(")", 0);
-
-
-
-
-
-