[Stack]主要栈操作

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://david.blog.csdn.net/article/details/52517794

栈的主要操作就是PUSH和POP。用PUSH方法把数据添加到栈里,用POP方法吧数据从栈中移除。下面用栈来计算简单的算是表达式。

        public  bool IsNumeric(string input) 
        {
            bool flag = true;
            string pattern=(@"^\d+$");
            Regex validate = new Regex(pattern);

            if (!validate.IsMatch(input))
            {
                flag = false;
            }
            return flag;
        }
        public 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 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;
            }
        }

测试:

            Stack nums=new Stack();
            Stack ops=new Stack ();
            string expression="5+10+15+20";

            CStack cs=new CStack ();
            cs.Calculate(nums,ops,expression);

            Console.WriteLine(nums.Pop());
            Console.Read();
展开阅读全文

没有更多推荐了,返回首页