IIT Bombay Data Structures and Algorithms Prof Ajit

IIT Bombay Data Structures and Algorithms Prof. Ajit A. Diwan Prof. Ganesh Ramakrishnan Prof. Deepak B. Phatak Department of Computer Science and Engineering IIT Bombay Session: Application of Stacks and Evaluation of Expressions Ajit A. Diwan, Ganesh Ramakrishnan, and Deepak B. Phatak, IIT Bombay 1

Application of Stacks IIT Bombay • Handling Expressions • Infix to Postfix and vice versa • Infix to Prefix and vice versa • Evaluating Postfix/Prefix Expressions • Backtracking • Maze • Chess • Memory Management Ajit A. Diwan, Ganesh Ramakrishnan, and Deepak B. Phatak, IIT Bombay 2

Infix Expressions IIT Bombay • Used in arithmetic • Operator is placed between the operands • Parentheses are used to denote the priority of the operation • Examples • a+b • (a + b) * (a - b) • (a ^ b * (c + (d * e) - f ) ) / g Ajit A. Diwan, Ganesh Ramakrishnan, and Deepak B. Phatak, IIT Bombay 3

Postfix Expressions IIT Bombay • Mathematical Notation • Operator is placed after all its operands • No need of parentheses • Easy to parse as compared to infix • Examples Infix Expression a+b (a + b) * (a - b) (a ^ b * (b + (d * e) - f ) ) / g Ajit A. Diwan, Ganesh Ramakrishnan, and Deepak B. Phatak, IIT Bombay Postfix Expressions ab+ab-* ab^cde*+f-*g/ 4

Evaluating Postfix Expressions IIT Bombay Example 1 (a=5, b=3) a b + a b - * 5 3 + 5 3 - * 8 2 * 16 (Answer) Example 2(a=4, b=2, c=5, d=6, e=7, f=8, g=3) a b ^ c d e * + f - * g / 4 2 ^ 5 6 7 * + 8 - * 3 / 16 5 42 + 8 - * 3 / 16 47 8 - * 3 / 16 39 * 3 / 624 3 / 208 (Answer) Ajit A. Diwan, Ganesh Ramakrishnan, and Deepak B. Phatak, IIT Bombay 5

Prefix Expressions IIT Bombay • Mathematical Notation • Operator is placed before all its operands • No need of parentheses • Easy to parse as compared to infix • Examples Infix Expression a+b (a + b) * (a - b) (a ^ b * (c + (d * e) - f ) ) / g Ajit A. Diwan, Ganesh Ramakrishnan, and Deepak B. Phatak, IIT Bombay Prefix Expressions +ab *+ab-ab /*^ab-+*decfg 6

Evaluating Prefix Expressions IIT Bombay Example 1 (a=5, b=3) * + a b - a b * + 5 3 - 5 3 * 8 2 16 (Answer) Example 2(a=4, b=2, c=5, d=6, e=7, f=8, g=3) / * ^ a b - + * d e c f g / * ^ 4 2 - + * 6 7 5 8 3 / * 16 - + 42 5 8 3 / * 16 47 8 3 / * 16 39 3 / 624 3 208 (Answer) Ajit A. Diwan, Ganesh Ramakrishnan, and Deepak B. Phatak, IIT Bombay 7

References IIT Bombay • https: //en. wikipedia. org/wiki/Stack_(abstract_data_type) • https: //en. wikipedia. org/wiki/Infix_notation • https: //en. wikipedia. org/wiki/Reverse_Polish_notation • https: //en. wikipedia. org/wiki/Polish_notation Ajit A. Diwan, Ganesh Ramakrishnan, and Deepak B. Phatak, IIT Bombay 8

IIT Bombay Thank you Ajit A. Diwan, Ganesh Ramakrishnan, and Deepak B. Phatak, IIT Bombay 9
- Slides: 9