Vous êtes sur la page 1sur 3

Applications of stack

Recursion:
n! = n * (n-1)!
If n=0 || n=1, n! = 1.
- It needs to use itself
- It has to end i.e. converge to termination
- It should limit towards termination condition.
Int fact (int n)
{
Int res;
If (n==0 || n==1)
Return 1;
Else
{
Res = n * fact (n-1);
Return res;
}
}
Evaluation of Expressions:
Infix Expressions:
3 + 4 infix expression (where operator is in between two
operands)
34+ - postfix expression (where operator is after operands)
+34 prefix expression (where operator is before operands)
3 + 4 * 5 / 6
= (3 + ((4 * 5) / 6))
= 3 + (4 5 *) / 6
= 3 + ( 4 5 * 6 / )
= ( 3 4 5 * 6 / + )
1. First convert the entire expression in postfix
2. Evaluate the postfix expression in simple order scanning
the expression only once.

Evaluation of postfix expression
3 4 5 * 6 / +
1. Start scanning the expression from left to right
a. When operand, push it to stack
b. When operator, pop two elements from stack,
perform the operation with that operator, push back
the result to stack.
2. Repeat the above step till end of expression. Answer is in
stack.

Expression stack
3 4 5 * 6 / + 3
4 5 * 6 / + 3, 4
5 * 6 / + 3, 4, 5
* 6 / + 3, 20
6 / + 3, 20, 6
/ + 3, 3
+ 6
NULL 6
Write a program which inputs directly the postfix expression,
evaluates and prints the result. That will be stored in array.
Just a function for evaluation needs to be written.

Vous aimerez peut-être aussi