// // This file contains the C# code from Program 6.12 of // "Data Structures and Algorithms // with Object-Oriented Design Patterns in C#" // by Bruno R. Preiss. // // Copyright (c) 2001--2002 by Bruno R. Preiss, P.Eng. All rights reserved. // // http://www.brpreiss.com/books/opus6/programs/pgm06_12.txt // public class Algorithms { public static void Calculator( TextReader reader, TextWriter writer) { Stack stack = new StackAsLinkedList(); int i; while ((i = reader.Read()) > 0) { char c = (char)i; if (Char.IsDigit(c)) stack.Push((int)c - (int)'0'); else if (c == '+') { int arg2 = (int)stack.Pop(); int arg1 = (int)stack.Pop(); stack.Push (arg1 + arg2); } else if (c == '*') { int arg2 = (int)stack.Pop(); int arg1 = (int)stack.Pop(); stack.Push (arg1 * arg2); } else if (c == '=') { int arg = (int)stack.Pop(); writer.WriteLine(arg); } } } }