//将前缀表达式转换为后缀表达式空格隔开每个元素 public static string toPostfixExpression(string str) { string rel = ""; int i = 0; Stack <char> sta = new Stack <char>(); while (true) { if (i >= str.Length) { break; } if (isNum(str[i])) { while (i < str.Length && isNum(str[i])) { rel += str[i]; i++; } rel += " "; } if (i < str.Length && !isNum(str[i])) { if (str[i] == ')') {//右括号 while (true) { char item = sta.Peek(); if (item == '(') { sta.Pop(); break; } else { rel += item; rel += " "; } sta.Pop(); } } else if (i < str.Length && sta.Count == 0 || str[i] == '(' || sta.Peek() == '(') {//栈顶为空或者遇见左括号或者当前栈顶是左括号 sta.Push(str[i]); } else {//栈顶优先级小于待入栈符号 while (i < str.Length && !(sta.Count() == 0) && !priority(str[i], sta.Peek())) { if (sta.Peek() != '(') { rel += sta.Peek(); rel += " "; } else { sta.Pop(); break; } sta.Pop(); } sta.Push(str[i]); } } i++; } while (!(sta.Count() == 0)) { if (sta.Peek() != '(') { rel += sta.Peek(); rel += " "; } sta.Pop(); } return(rel); }
/** * 中缀转后缀 */ private Queue <string> change(string str) { string temp = ""; string str1 = ""; Stack <string> s = new Stack <string>(); Queue <string> que = new Queue <string>(); int i; for (i = 0; i < str.Length; i++) { temp = ""; if (((i == 0) && (str[i] == '+' )) || (str[i] >= '0' && str[i] <= '9')) { if (i >= str.Length) { break; } while (i < str.Length && (((i == 0) && (str[i] == '+')) || (str[i] >= '0' && str[i] <= '9' || str[i] == '.'))) { if (str[i] != '+') { temp += str[i]; } i++; } if (temp.Length > 0) { que.Enqueue(temp); } } if (i >= str.Length) { break; } if (str[i] == '*' || str[i] == '/' || str[i] == '%') { str1 = str[i].ToString(); s.Push(str1); } else if (str[i] == '+' || str[i] == '-') { if (s.Count() == 0) { str1 = str[i].ToString(); s.Push(str1); } else { do { str1 = s.Peek(); s.Pop(); que.Enqueue(str1); } while (s.Count() != 0); str1 = str[i].ToString(); s.Push(str1); } } str1 = ""; } while (s.Count() > 0) { str1 = s.Peek(); s.Pop(); que.Enqueue(str1); } //string num = ""; //foreach (var val in que) // num += val.ToString(); //MessageBox.Show(num); return(que); }
public static int Calculate(string calculation) { if (string.IsNullOrEmpty(calculation) || string.IsNullOrWhiteSpace(calculation)) { throw new Exception("Empty String passed"); } string[] tokens = calculation.Split(' '); Stack <Operation> operationStack = new Stack <Operation>(); foreach (var token in tokens) { switch (token) { case "(": operationStack.Push(new Operation()); break; case ")": int value = calculateValue(operationStack.Pop()); if (operationStack.Count() == 0) { return(value); } Operation above = operationStack.Peek(); if (above.Value1 == 0) { above.Value1 = value; } else if (above.Value2 == 0) { above.Value2 = value; } else { above.Value3 = value; } break; case "add": operationStack.Peek().Operator = "add"; break; case "mult": operationStack.Peek().Operator = "mult"; break; default: Operation currentOperation = operationStack.Peek(); int IntegerRepresentation = Convert.ToInt16(token); if (currentOperation.Value1 == 0) { currentOperation.Value1 = IntegerRepresentation; } else if (currentOperation.Value2 == 0) { currentOperation.Value2 = IntegerRepresentation; } else { currentOperation.Value3 = IntegerRepresentation; } break; } } if (operationStack.Count() != 1) { throw new Exception("Input string was unbalanced"); } return(calculateValue(operationStack.Pop())); }
private static string ConvertExpressionToRPN(string inputExpression) { string output = string.Empty; Stack<string> operatorStack = new Stack<string>(); int countChars; int legthInputExpression = inputExpression.Length; for (countChars = 0; countChars < legthInputExpression; countChars++) { // Parse number in input expression if (Char.IsDigit(inputExpression[countChars]) || inputExpression[countChars] == '.') { while(!IsSimpleOperator(inputExpression[countChars])) { output += inputExpression[countChars]; countChars++; if (countChars == legthInputExpression) { break; } } output += " "; countChars--; } if (IsSimpleOperator(inputExpression[countChars])) { if (inputExpression[countChars] == '(') { operatorStack.Push(inputExpression[countChars].ToString()); } if (inputExpression[countChars] == ')') { string itemsAtBracket = operatorStack.Pop(); // items from stack to output string while (itemsAtBracket != "(") { output += itemsAtBracket + " "; itemsAtBracket = operatorStack.Pop(); } } if (inputExpression[countChars] != '(' && inputExpression[countChars] != ')') { // Adding operator to stack if not open|close quote if (operatorStack.Count() > 0 && GetPriorytyForItem(inputExpression[countChars].ToString()) <= GetPriorytyForItem(operatorStack.Peek())) { output += operatorStack.Pop() + " "; } operatorStack.Push(inputExpression[countChars].ToString()); } } } // Output items From stack to output string while (operatorStack.Count > 0) { output += operatorStack.Pop() + " "; } return output.Trim(); }
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); }