Ejemplo n.º 1
0
        //Part 2: Complete this method to evaluate Postfix Expressions using MyListStack
        static int EvaluatePostFix(string[] stringItems, MyListStack stack)
        {
            // Cycle through string array for various operations
            for (int i = 0; i < stringItems.Length; i++)
            {
                int  temp;
                bool isNumeric = int.TryParse(stringItems[i], out temp);
                if (isNumeric) // if index is a number
                {
                    stack.Push(temp);
                }
                else // if index is an operation
                {
                    int first  = stack.Pop();
                    int second = stack.Pop();
                    int total  = 0;

                    // Switch for mathematic operations
                    switch (stringItems[i])
                    {
                    case "+":
                        total = first + second;
                        Console.Write("(" + first + " + " + second + ")\n");
                        stack.Push(total);
                        break;

                    case "-":
                        total = first - second;
                        Console.Write("(" + first + " - " + second + ")\n");
                        stack.Push(total);
                        break;

                    case "*":
                        total = first * second;
                        Console.Write("(" + first + " * " + second + ")\n");
                        stack.Push(total);
                        break;

                    case "/":
                        total = first / second;
                        Console.Write("(" + first + " / " + second + ")\n");
                        stack.Push(total);
                        break;

                    case "%":
                        total = first % second;
                        Console.Write("(" + first + " % " + second + ")\n");
                        stack.Push(total);
                        break;
                    } // switch
                }     // else
            }         // for
            return(stack.Pop());
        }