C#实现逆波兰表达式求解四则混合运算的值

代码如下:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string expression = "2*(3+4)";
            List<string> infixExpressionList = GetExpressionList(expression);

            // 获取中缀表达式
            Console.Write("中缀表达式:");
            foreach (string code in infixExpressionList)
            {
                Console.Write(code);
            }
            Console.WriteLine();

            // 转换为逆波兰表达式
            Console.Write("后缀表达式:");
            List<string> postfixExpressionList = GetReversePolishNotation(infixExpressionList);
            foreach (string code in postfixExpressionList)
            {
                Console.Write(code);
            }
            Console.WriteLine();

            // 计算结果
            Console.Write("运算结果:");
            double result = CalculateReversePolishNotation(postfixExpressionList);
            Console.WriteLine(result);
            Console.ReadKey();
        }

        /// <summary>
        /// 是否为操作数
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        static bool IsNumber(string code)
        {
            double number = 0;
            return double.TryParse(code, out number);
        }

        /// <summary>
        /// 是否为运算符
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        static bool IsOperator(string code)
        {
            return code == "(" || code == ")" || code == "+" || code == "-" || code == "*" || code == "/";
        }

        /// <summary>
        /// 获取运算符优先级
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        static int GetOperatorPriority(string code)
        {
            int priority = 0;
            switch (code)
            {
                case "+":
                    priority = 1;
                    break;
                case "-":
                    priority = 1;
                    break;
                case "*":
                    priority = 2;
                    break;
                case "/":
                    priority = 2;
                    break;
                default:
                    priority = 0;
                    break;
            }
            return priority;
        }

        /// <summary>
        /// 计算两个操作数的结果
        /// </summary>
        /// <param name="code"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        static double GetValue(string code, double x, double y)
        {
            double result = 0;
            switch (code)
            {
                case "+":
                    result = x + y;
                    break;
                case "-":
                    result = x - y;
                    break;
                case "*":
                    result = x * y;
                    break;
                case "/":
                    result = x / y;
                    break;
            }
            return result;
        }

        /// <summary>
        /// 解析四则混合运算表达式
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        static List<string> GetExpressionList(string expression)
        {
            HashSet<char> hashset = new HashSet<char>();
            hashset.Add('(');
            hashset.Add(')');
            hashset.Add('+');
            hashset.Add('-');
            hashset.Add('*');
            hashset.Add('/');

            // 获取各项
            List<string> list = new List<string>();
            List<string> temp = new List<string>();
            for (int i = 0; i < expression.Length; i++)
            {
                char code = expression[i];
                if (hashset.Contains(code))
                {
                    list.Add(code.ToString());
                }
                else
                {
                    temp.Add(code.ToString());
                    if (i + 1 < expression.Length)
                    {
                        if (hashset.Contains(expression[i + 1]))
                        {
                            string number = null;
                            for (int j = 0; j < temp.Count; j++)
                            {
                                number += temp[j];
                            }
                            list.Add(number);
                            temp.Clear();
                        }
                    }
                    else
                    {
                        string number = null;
                        for (int j = 0; j < temp.Count; j++)
                        {
                            number += temp[j];
                        }
                        list.Add(number);
                        temp.Clear();
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取逆波兰表达式
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        static List<string> GetReversePolishNotation(List<string> list)
        {
            Stack<string> operatorStack = new Stack<string>();    // 运算符栈
            Stack<string> operandStack = new Stack<string>();     // 操作数栈

            // 遍历运算符
            foreach (string text in list)
            {
                if (IsNumber(text))
                {
                    operandStack.Push(text);
                }
                else
                {
                    if (text == "(")
                    {
                        operatorStack.Push(text);
                    }
                    else if (text == ")")
                    {
                        while (operatorStack.Peek() != "(")
                        {
                            operandStack.Push(operatorStack.Pop());
                        }
                        operatorStack.Pop();
                    }
                    else
                    {
                        if (operatorStack.Count() == 0 || operatorStack.Peek() == "(")
                        {
                            operatorStack.Push(text);
                        }
                        else
                        {
                            if (GetOperatorPriority(text) >= GetOperatorPriority(operatorStack.Peek()))
                            {
                                operatorStack.Push(text);
                            }
                            else
                            {
                                operandStack.Push(operatorStack.Pop());
                                operatorStack.Push(text);
                            }
                        }
                    }
                }
            }

            // 遍历剩余运算符
            while (operatorStack.Count() > 0)
            {
                operandStack.Push(operatorStack.Pop());
            }

            // 反转运算符顺序
            List<string> result = new List<string>();
            while (operandStack.Count() > 0)
            {
                result.Add(operandStack.Pop());
            }
            result.Reverse();
            return result;
        }

        /// <summary>
        /// 计算逆波兰表达式
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        static double CalculateReversePolishNotation(List<string> list)
        {
            Stack<double> stack = new Stack<double>();
            foreach (string text in list)
            {
                if (IsOperator(text))
                {
                    double a = stack.Pop();
                    double b = stack.Pop();
                    stack.Push(GetValue(text, b, a));
                }
                else
                {
                    stack.Push(double.Parse(text));
                }
            }
            return stack.Pop();
        }
    }
}

运行结果如下:

中缀表达式:2*(3+4)
后缀表达式:234+*
运算结果:14
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值