/// <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()); }
public ArrayList InputToPostfix() { Stack <Token> operatorStack = new Stack <Token>(); ArrayList postfixExpr = new ArrayList(); //loop over the tokenized infix expression from user input try { foreach (Token currToken in inputTokens) { //if current token is an operand, add to output expression if (currToken is Operand) { postfixExpr.Add(currToken); } else if (currToken is Operator) { //if current operator is a '(', add it to op stack if (currToken.getValue().Equals("(")) { operatorStack.Push(currToken); } //if current operator is a ')', pop from stack and add to output until '(' is encountered else if (currToken.getValue().Equals(")")) { Token topStackToken = operatorStack.Pop(); while (!(topStackToken.getValue().Equals("("))) { postfixExpr.Add(topStackToken); topStackToken = operatorStack.Pop(); } } //operators that are not parentheses else { Operator currOpToken = currToken as Operator; Operator currStackToken = new Operator(""); while ((!(operatorStack.Count() == 0)) && ((currStackToken = (Operator)operatorStack.Peek()).getPriority() >= currOpToken.getPriority())) { //add tokens from stack to output expression while the current token has <= priority than top of stack currStackToken = operatorStack.Pop() as Operator; postfixExpr.Add(currStackToken); } operatorStack.Push(currToken); } } } } catch (System.InvalidOperationException) { return(new ArrayList()); } //add remainder of stack to postfix expression while (!(operatorStack.Count() == 0)) { postfixExpr.Add(operatorStack.Pop()); } return(postfixExpr); }