1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| public static string ParseToRPN(string pattern) { StringBuilder Rexpression = new StringBuilder();
pattern = ReplaceUnleagalChar(pattern); Stack<double> num = new Stack<double>(); Stack<char> oper = new Stack<char>(); StringBuilder stringBuilder = new StringBuilder(); bool flag = false; for (int i = 0; i < pattern.Length; i++) { if (char.IsDigit(pattern[i]) || pattern[i] == '.' || (i == 0 && pattern[i] == '-') || (i > 0 && pattern[i - 1] == '(')) { stringBuilder.Append(pattern[i]); } else { if (!string.IsNullOrWhiteSpace(stringBuilder.ToString())) num.Push(double.Parse(stringBuilder.ToString())); if (stringBuilder.Length > 1) { Rexpression.Append($"({stringBuilder})"); } else Rexpression.Append(stringBuilder.ToString()); stringBuilder.Clear(); flag = pattern[i] == '('; PushOperators(ref oper, ref Rexpression, pattern[i]); } } if (!string.IsNullOrWhiteSpace(stringBuilder.ToString())) { if (stringBuilder.Length > 1) Rexpression.Append($"({stringBuilder})"); else Rexpression.Append(stringBuilder.ToString()); } while (oper.Count > 0) Rexpression.Append(oper.Pop()); Console.WriteLine($"逆波兰表达式:{Rexpression}"); return Rexpression.ToString(); } public static string ReplaceUnleagalChar(string p) { return p.Replace("(", "(").Replace(")", ")").Replace("÷", "/").Replace("×", "*") .Replace("x", "*").Replace("除以", "/").Replace("除", "/").Replace("乘以", "*").Replace("乘", "*").Replace(" ", ""); } public static void PushOperators(ref Stack<char> opers, ref StringBuilder Rexpression, char oper) { if (opers.Count == 0) opers.Push(oper); else if (oper == ')') { while (opers.Count != 0 && opers.Peek() != '(') Rexpression.Append(opers.Pop()); opers.Pop(); } else if (operators[oper] > operators[opers.Peek()]) opers.Push(oper); else { while (opers.Count != 0 && opers.Peek() != '(' && operators[oper] <= operators[opers.Peek()]) Rexpression.Append(opers.Pop()); opers.Push(oper); } }
|