您的位置:首页 > 其它

简单的用堆栈实现的表达式计算

2013-04-25 14:20 330 查看
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace 简单表达式求解
{
class Program
{
static void Main(string[] args)
{
Stack numbs = new Stack();
Stack ops = new Stack();

String expression = "5 + 10 - 15 * 20 * 2";

Calculate(numbs, ops, expression);

Console.WriteLine(numbs.Pop());
}

public static bool IsNumeric(string input)
{
bool flag = true;

string pattern = "^\\d+$";

Regex validate = new Regex(pattern);

if (!validate.IsMatch(input))
{
flag = false;
}

return flag;
}

public static void Calculate(Stack n, Stack o, string exp)
{
string ch, token = "";

for (int p = 0; p < exp.Length; p++)
{
ch = exp.Substring(p, 1);
if (IsNumeric(ch))
{
token += ch;
}

if (ch == " " || p == (exp.Length - 1))
{
if (IsNumeric(token))
{
n.Push(token);
token = "";
}
}
else if (ch == "+" || ch == "-" || ch == "*" || ch == "/")
{
o.Push(ch);
}

if (n.Count == 2)
{
Compute(n, o);
}
}
}

public static void Compute(Stack n, Stack o)
{
int oper1, oper2;

string oper;

oper1 = Convert.ToInt32(n.Pop());
oper2 = Convert.ToInt32(n.Pop());

oper = Convert.ToString(o.Pop());
switch (oper)
{
case "+":
n.Push(oper1 + oper2);
break;
case "-":
n.Push(oper1 - oper2);
break;
case "*":
n.Push(oper1 * oper2);
break;
case "/":
n.Push(oper1 / oper2);
break;
}

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: