//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()); }
static void Main(string[] args) { MyListStack myStack = new MyListStack(); string testString = "56+2*1+"; // Create string array string[] stringItems = new string[testString.Count()]; // Turn string into string array for (int i = 0; i < testString.Length; i++) { stringItems[i] = testString[i].ToString(); } //debugging //for (int i = 0; i < stringItems.Length; i++) //{ // Console.Write(stringItems[i]); //} // Output Format Console.WriteLine("Stack Input:"); Console.WriteLine(testString); Console.WriteLine("Press any key to calculate total...\n"); Console.ReadKey(); Console.WriteLine("Stack Output:"); // Run Instance int result = EvaluatePostFix(stringItems, myStack); // Output Format Console.WriteLine("\nTotal: " + result); Console.WriteLine("Press any key to close application."); Console.ReadKey(); }