using System; using System.Collections.Generic; class InfixToPostfix { static int Precedence(char op) { switch (op) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; default: return 0; } } static bool IsOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/' || c == '^'; } public static string Convert(string infix) { Stack stack = new Stack(); string postfix = ""; for (int i = 0; i < infix.Length; i++) { char c = infix[i]; if (c == ' ') continue; if (Char.IsLetterOrDigit(c)) { postfix += c; } else if (c == '(') { stack.Push(c); } else if (c == ')') { while (stack.Count > 0 && stack.Peek() != '(') { postfix += stack.Pop(); } if (stack.Count > 0 && stack.Peek() == '(') stack.Pop(); // Bỏ dấu '(' } else if (IsOperator(c)) { while (stack.Count > 0 && Precedence(stack.Peek()) >= Precedence(c)) { postfix += stack.Pop(); } stack.Push(c); } } while (stack.Count > 0) { postfix += stack.Pop(); } return postfix; } static void Main() { Console.Write("Nhap bieu thuc infix: "); string infix = Console.ReadLine(); string postfix = Convert(infix); Console.WriteLine("bieu thuc postfix: " + postfix); } }