Ejemplo n.º 1
0
        // The main method that converts given infix expression
        // to postfix expression.
        public static String infixToPostfix(String exp)
        {
            // initializing empty String for result
            var result = "";

            // initializing empty stack
            var stack = new GenericStack <char>();

            for (int i = 0; i < exp.Length; ++i)
            {
                var c = exp[i];

                // If the scanned character is an operand, add it to output.
                if (Char.IsLetterOrDigit(c))
                {
                    result += c;
                }

                // If the scanned character is an '(', push it to the stack.
                else if (c == '(')
                {
                    stack.push(c);
                }

                //  If the scanned character is an ')', pop and output from the stack
                // until an '(' is encountered.
                else if (c == ')')
                {
                    while (!stack.isEmpty() && stack.peek() != '(')
                    {
                        result += stack.pop();
                    }

                    if (!stack.isEmpty() && stack.peek() != '(')
                    {
                        return("Invalid Expression"); // invalid expression
                    }
                    else
                    {
                        stack.pop();
                    }
                }
                else // an operator is encountered
                {
                    while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek()))
                    {
                        result += stack.pop();
                    }
                    stack.push(c);
                }
            }

            // pop all the operators from the stack
            while (!stack.isEmpty())
            {
                result += stack.pop();
            }

            return(result);
        }
Ejemplo n.º 2
0
 public static void ConverTo(GenericStack <int> dStack, GenericQueue <int> dQueue)
 {
     while (!dStack.isEmpty())
     {
         var tmp = dStack.peek();
         dQueue.Enqueue(tmp);
         dStack.pop();
     }
     Console.WriteLine(dQueue);
 }