/// <summary> /// 计算 /// </summary> /// <param name="ops">操作符的反向栈</param> /// <param name="nums">操作数的反向栈</param> /// <returns>最终结果</returns> public static int Calculate(Stack ops, Stack nums) { // 生成两个栈供使用 Stack opStack = new Stack(); Stack numStack = new Stack(); // 开始入栈计算 numStack.Push(nums.Pop()); while (nums.Count != 0) { numStack.Push(nums.Pop()); Operator thisOp = (Operator)ops.Pop(); if (ops.Count != 0) { Operator nextOp = (Operator)ops.Peek(); // 比较优先级,若当前运算符优先级大于等于下一个运算符,则先运算 if (thisOp.getPriority() >= nextOp.getPriority()) { int x2 = (int)numStack.Pop(); int x1 = (int)numStack.Pop(); int result = thisOp.doCal(x1, x2); numStack.Push(result); } else { opStack.Push(thisOp); } } else { opStack.Push(thisOp); } } // 确保运算完全完成 Stack restOps = new Stack(opStack); Stack restNums = new Stack(numStack); while (restOps.Count != 0) { int x1 = (int)restNums.Pop(); int x2 = (int)restNums.Pop(); restNums.Push(((Operator)restOps.Pop()).doCal(x1, x2)); } return((int)restNums.Pop()); }