100 likes | 196 Views
COP 3502 Spring 2005 Christopher Elwell. Lab Session 5. Administrivia. Recitation notes duplicated online: http://www.cs.ucf.edu/~celwell Office Hours MTWF 2-4 PM Quizzes and Tests Quizzes may be given at any time (lab or class) Assignment 1 Should have been submitted
E N D
COP 3502 Spring 2005 Christopher Elwell Lab Session 5
Administrivia • Recitation notes duplicated online: • http://www.cs.ucf.edu/~celwell • Office Hours • MTWF 2-4 PM • Quizzes and Tests • Quizzes may be given at any time (lab or class) • Assignment 1 • Should have been submitted • Cutoff date (with penalty) 2/10/05
Postfix Expressions • Solve using a stack • When you encounter a number, push it onto the stack • When you encounter an operator (*, /, +, -) • Pop two numbers from the stack • Perform the operation • Push the result onto the stack
Postfix Expressions 1.) 6 7 9 + - 2.) 6 7 9 + - 2 / 11 2 2 / + * 3.) 2 8 – 12 * 2 5 6 + - / 3 3 / * 4.) 4 4 4 4 + - * 2 4 + + 5 / 3 *
Postfix Expressions 1.) 6 7 9 + - = -10 2.) 6 7 9 + - 2 / 11 2 2 / + * = -60 3.) 2 8 – 12 * 2 5 6 + - / 3 3 / * = 8 4.) 4 4 4 4 + - * 2 4 + + 5 / 3 * = -6
Converting Infix to Postfix • General Algorithm: • Process from left to right • Copy numbers directly to the output • Use stack for operators • Always push ( onto the stack • When you encounter ), pop symbols off the stack until you reach the preceding ( (discard both parentheses) • Operators: • If the operator being “scanned” has higher precedence than the symbol at the stack top, push that symbol onto the stack • Otherwise, pop • Pop all operators off stack when you reach end of expression.
Converting Infix to Postfix 1.) X*Y-(P+Q)*(R/S) 2.) E-F*G/(P+Q)+T 3.) M+L/K*U
Converting Infix to Postfix 1.) X*Y-(P+Q)*(R/S) = XY*PQ+RS/*- 2.) E-F*G/(P+Q)+T = EFG*PQ+/-T+ 3.) M+L/K*U = MLK/U*+
Valid? 1.) 3 5 7 - + 3 2 9 * / - 2.) 4 3 – 2 3 * 5 8 - + 4 - * 2 + 3.) 7 5 3 - + 3 / * 4 2 +
Valid? 1.) 3 5 7 - + 3 2 9 * / - Valid 2.) 4 3 – 2 3 * 5 8 - + 4 - * 2 + Valid 3.) 7 5 3 - + 3 / * 4 2 + Invalid