140 likes | 291 Views
COMP 121. Week 13. Outcomes. List the typical operations and properties of stacks as distinct from other collections. Implement operations on stacks and justify design decisions. Analyze the stack implementation to determine algorithmic efficiency.
E N D
COMP 121 Week 13
Outcomes • List the typical operations and properties of stacks as distinct from other collections. • Implement operations on stacks and justify design decisions. • Analyze the stack implementation to determine algorithmic efficiency. • Use a stack data structure to solve a problem.
Learning Activities Activity 13-1 Outcome: List the typical operations and properties of stacks as distinct from other collections. Activity 13-2 Outcome: Implement operations on stacks and justify design decisions.
Learning Activities Activity 13-3 Outcome: Analyze the stack implementation to determine algorithmic efficiency.
Converting Infix to Postfix Example (a + b) * d + e / (f + a * d) + c a b + d * e f a d * + / + c +
Converting Infix to Postfix • Add operands directly to the output string • Left parenthesis: Push onto the stack • Right parenthesis: Pop from the stack all operators up to and including the first left parenthesis, adding operators to the output string. • Operator: Pop all operators of greater or equal precedence, adding them to the output string. The operator just read is pushed onto the stack. • End: Pop the remaining operators and add them in turn to the end of the output string.
Evaluating Postfix Expressions Example 2 3 4 + * 14 6 2 / 3 – 4 2 * + 8
Evaluating Postfix Expressions • Push operands onto the stack • When an operator is read, it is applied to the top two operands on the stack after they have been popped, and the result is pushed onto the stack. If the operator is unary, only one operand is popped, the operator is applied, and the result is pushed back onto the stack. • When all characters in the postfix expression have been scanned, the result can be found on top of the stack.
4 7 4 28 20 28 8 Expression Action Stack 4 7 * 20 - Push 4 4 7 * 20 - Push 7 4 7 * 20 - Pop 7 and 4 Evaluate 4 * 7 Push 28 4 7 * 20 - Push 20 4 7 * 20 - Pop 20 and 28 Evaluate 28 – 20 Push 8 4 7 * 20 - Pop 8 Stack is empty Result is 8
Learning Activities Activity 13-4 Outcome: Use a stack data structure to solve a problem.
Homework Assignments • Due this week • SubListHW • Due next week • Lab 5 • StackHW