Download presentation
Presentation is loading. Please wait.
1
Queue Applications Lecture 31 Mon, Apr 9, 2007
2
Infix Expression Evaluation
An infix expression with one (binary) operator is written in the order: left-operand, operator, right-operand. Example: 2/23/2019 Queues
3
Disadvantages of Infix Notation
Parentheses are often needed to indicate order of operation. Example: (3 + 4) * (5 + 6) Operators follow a precedence hierarchy. Example: * 5 – 6 / 7 Operators have left or right associativity. Example: 100 – 50 – 10 – 5 – 1 2/23/2019 Queues
4
Infix Expression Evaluation
To evaluate an infix expression, we first convert it to postfix. Then begin with an empty stack and an empty queue. Process the tokens from left to right according to the following rules. If the token is a number, Enqueue the token. If the token is a left parenthesis, Push the token onto the stack. 2/23/2019 Queues
5
Infix Expression Evaluation
If the token is a right parenthesis, Pop tokens off the stack and enqueue them until a left parenthesis is popped. Discard the right and left parentheses. 2/23/2019 Queues
6
Infix Expression Evaluation
If the token is an operator, Pop tokens off the stack and enqueue them until An operator of lower precedence is on top of the stack, or A left parenthesis is on top of the stack, or The stack is empty. Push the operator onto the stack. 2/23/2019 Queues
7
Infix Expression Evaluation
After processing the last token Pop all tokens off the stack and enqueue them. The queue now contains the expression in post-fix notation. Process the queue as a post-fix expression. 2/23/2019 Queues
8
Example Convert the expression ((1 + 2)*3 – 4/(5 + 6 – 7*8))*9 7
from infix to postfix notation. 2/23/2019 Queues
9
Example Input token Stack Queue ( ( ( 1 + ( ( + 2 1 2 ) 1 2 + * ( * 3
– ( – * 2/23/2019 Queues
10
Example Input token Stack Queue 4 ( – 1 2 + 3 * 4 / ( – / ( ( – / ( 5
* 4 5 + ( – / ( + 6 * 4 5 6 – ( – / ( – * 7 * * ( – / ( – * 2/23/2019 Queues
11
Example Input token Stack Queue 8 ( – / ( – * 1 2 + 3 * 4 5 6 + 7 8 )
* * – * * – / – * 9 * * – / – 9 eof * * – / – 9 * 2/23/2019 Queues
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.