Example of Stacks: Infix, Postfix and Prefix
Example of Stacks: Infix, Postfix and Prefix
– ( (AB+)*C-(DE-) ) $ (FG+)
– ( (AB+C*)-(DE-) ) $ (FG+)
– (AB+C*DE--) $ (FG+)
– AB+C*DE- -FG+$
} /* end while */ * 1 7 7 7
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
/ 8 2 4 1,3,4
+ 3 4 7 1,7
* 1 7 7 7
2 1 7 7 7,2
$ 7 2 49 49
Conversion of Infix Expression to
postfix
A+B*C = ABC*+
(A+B)*C = AB+C*
There must be a precedence function.
prcd(op1, op2), where op1 and op2 are characters representing operators.
This function returns TRUE if op1 has precedence over op2 when op1 appears to the
left of op2 in an infix expression without parenthesis. prcd(op1,op2) returns FALSE
otherwise.
For example prcd(‘*’,’+’) and prcd(‘+’,’+’) are TRUE whereas prcd(‘+’,’*’) is FALSE.
prcd(‘$’,’$’) = FALSE
prcd( op, ‘(‘ ) = FALSE for any operator op other than ‘)’
prcd( op, ‘)‘ ) = TRUE for any operator op other than ‘(‘
} /* end else */
} /* end while */
/* output any remaining operators */
while (!empty(opstk) ) {
topsymb = pop(opstk);
add topsymb to the postfix string;
} /* end while */
Algorithm to Convert Infix to Postfix
opstk = the empty stack; Example-3: ( (A-(B+C) ) *D ) $ (E+F)
while (not end of input) {
symb = next input character; symb Postfix string opstk
if (symb is an operand) ( (
add symb to the postfix string ( ((
else {
A A ((
while (!empty(opstk) && prcd(stacktop(opstk),symb) )
{ - A ((-
topsymb = pop(opstk); ( A ((-(
add topsymb to the postfix string;
B AB ((-(
} /* end while */
+ AB ((-(+
If (empty(opstk) || symb != ‘)’ ) C ABC ((-(+
push(opstk, symb);
) ABC+ ((-
else
topsymb = pop(opstk); ) ABC+- (
* ABC+- (*
} /* end else */
D ABC+-D (*
} /* end else */
} /* end while */
/* output any remaining operators */
while (!empty(opstk) ) {
topsymb = pop(opstk);
add topsymb to the postfix string;
} /* end while */
Factorial of a number
• Write function to calculate the factorial of a
number.
– Iterative definition
– Recursive