标签:
1.测试代码
public class MyClass { public static void Run() { KExpression exp = new KExpression(); string backExp = exp.GetRPN("1+3*(4+6/2)"); string value = exp.GetValue(backExp); } }
2.把计算公式转后缀表达式,去掉其中的括号
/// <summary> /// 把中缀表达式转为后缀表达式 /// </summary> /// <param name="p"></param> /// <returns></returns> public string GetRPN(string p) { Stack<char> stack = new Stack<char>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < p.Length; i++) { char h = p[i]; if (IsOperator(h) && stack.Count == 0)//rule 2如果是操作数并且栈为空,把操作数入栈 { stack.Push(h); } else if (char.IsDigit(h))// rule 1 { sb.Append(h); } else if (h == ‘(‘) //rule 3 { stack.Push(h); } else if (h == ‘)‘) //rule 4 找出与该括号匹配的左括号 { while (true) { var t = stack.Pop(); if (t == ‘(‘) { break; } sb.Append(t); } } else if (IsOperator(h) && stack.Count > 0)//rule 5 { var t = stack.Peek(); if (Prop(t) >= Prop(h)) { t = stack.Pop(); sb.Append(t); } else { stack.Push(h); } } } while (stack.Count > 0) { var t = stack.Pop(); sb.Append(t); } return sb.ToString(); }
标签:
原文地址:http://www.cnblogs.com/363546828/p/5101860.html