49. Stack-2: (Prefix/Infix/Postfix)

Note-

These are just different notations to write logical expressions.

Infix- (operator is b/w operands + human friendly + need brackets )
Prefix- (operator comes before operands + evaluate right to left)
Postfix- (operator comes after operands + evaluate left to right )

Priority order of operators:       (^)    >    ( *, / )    >    (+, -)
Prefix & postfix notation, do not require machines to have precedence rules.
------------------------------------------------------
# Learn, Infix to Postfix conversion (c1, say)
2. Infix to Prefix is modified c1
--------
# For other conversions (2.1, 2.2, 3.1, 3.2) 
traverse from the side, where operands come before operator⭐
---------------------------------------------------------------------------------------------------------------

1.1 Infix to Postfix-⭐

we can return numbers for each operator, and then compare the precedance.

Model-
Operators wait in stack till both operands are ready
-----------------------

----------------------------------------------------------------------------------------------------------------------------

1.2 Infix to Prefix-

1. reverse the given string & invert all brackets
2. do infix to postfix conversion
3. reverse the answer
---------------------------

---------------------------------------------------------------------------------------------------------------------------

2.1 Postfix to Infix-
(expression building)

1. iterate from left to right
2. if element is operand => push into stack
3. if it is an operator => pick last 2 elements from stack & push: (top1 # top2)
-----------
- when iteration is over, stack only contains 1 element (final infix expression) which is our answer
- this time we need a stack of string data type

-----------------------------------------------------------------------------------------------------------------------------

2.2 Prefix to Infix-

iterate from right to left (since operands on right in prefix)
else, exactly same logic as of 2.1

-----------------------------------------------------------------------------------------------------------------------------

3.1 Postfix to Prefix-

iterate from left to right (since we have operands on left in postfix)
1. if element is operand, push it into stack
2. if u see an operator, pop out last 2 operands from stack & push: ( # top2 top1 ) 

----------------------------------------------------------------------------------------------------------------------------

3.2 Prefix to Postfix-

1. iterate from right to left (since right side in prefix has operands)
2. if element = operand, push into stack
3. else, pop out last 2 top operands from stack & push: ( top1 top2 # )

---------------------------------------------------------------------------------------------------------------------------

Comments

Popular posts from this blog

30.) DP on subsequences

36. Graphs-2 (traversal problems)

35. Graphs-1 (basics)