简单的用堆栈实现的表达式计算
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; } } } }
相关文章推荐
- 简单的用堆栈实现的表达式计算
- Java堆栈的应用2----------中缀表达式转为后缀表达式的计算Java实现
- 堆栈的应用(2) 中缀算术表达式到后缀(逆波兰记法reverse polish notation)的转换及其计算 C++实现
- VB利用堆栈实现表达式计算
- Java实现简单的表达式计算
- 使用堆栈计算后缀表达式--java实现
- Clojure: 实现简单的数学表达式计算
- VC++2012编程演练数据结构《5》堆栈实现解析任意计算表达式
- VC++2012编程演练数据结构《5》堆栈实现解析任意计算表达式
- JAVA实现一个简单的代数运算语言编译器(四)-- 表达式计算
- 关于Java写逆波兰表达式堆栈操作简单实现
- 利用数组模拟栈实现简单的表达式中缀转后缀并进行计算
- 堆栈实现中缀表达式转后缀表达式及计算表达式的值
- 堆栈的应用(2) 中缀算术表达式到后缀(逆波兰记法reverse polish notation)的转换及其计算 C++实现
- [置顶] 编译原理---四则运算表达式的计算简单实现
- Qt实现的简单计算器-计算简单表达式
- 使用栈计算多项表达式的简单实现--java
- 堆栈实现,计算后缀表达式
- 简单的表达式计算
- 算式类型字符串表达式读取并计算出结果(简单四则运算)--后缀表达式计算