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

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;
            }

        }
    }
}

posted on 2013-04-25 14:20  Yours风之恋  阅读(239)  评论(0编辑  收藏  举报