private static String InfixToPostfix(string infix) { String postfix = ""; var st = new StackArray <char>(20); char next, symbol; for (int i = 0; i < infix.Length; i++) { symbol = infix[i]; if (symbol == ' ' || symbol == '\t') { continue; } switch (symbol) { case '(': st.Push(symbol); break; case ')': while ((next = st.Pop()) != '(') { postfix = postfix + next; } break; case '+': case '-': case '*': case '/': case '%': case '^': while (!st.IsEmpty() && Precedence(st.Peek()) >= Precedence(symbol)) { postfix = postfix + st.Pop(); } st.Push(symbol); break; default: //hopefully an operand postfix = postfix + symbol; break; } } while (!st.IsEmpty()) { postfix = postfix + st.Pop(); } return(postfix); }
public static int EvaluatePostfix(String postfix) { var st = new StackArray <int>(50); int x, y; for (int i = 0; i < postfix.Length; i++) { if (Char.IsDigit(postfix[i])) { st.Push(Convert.ToInt32(Char.GetNumericValue(postfix[i]))); } else { x = st.Pop(); y = st.Pop(); switch (postfix[i]) { case '+': st.Push(y + x); break; case '-': st.Push(y - x); break; case '*': st.Push(y * x); break; case '/': st.Push(y / x); break; case '%': st.Push(y % x); break; case '^': st.Push(power(y, x)); break; } } } return(st.Pop()); }