49. Stack-2: (Prefix/Infix/Postfix)
# Note-
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⭐
---------------------------------------------------------------------------------------------------------------
we can return numbers for each operator, and then compare the precedance.
Model-
Operators wait in stack till both operands are ready
-----------------------
1. reverse the given string & invert all brackets
2. do infix to postfix conversion
3. reverse the answer
---------------------------
(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
iterate from right to left (since operands on right in prefix)
else, exactly same logic as of 2.1
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 )
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
Post a Comment