Application of Stack
Application of Stack
Kalpoma 1
Application of stack continuation……
• Syntax parsing, Expression evaluation and
Expression conversion.
• Towers of Hanoi
• Validation
1. There is an equal number of closing and opening
parentheses
2. Every closing parenthesis is preceded by a
matching opening parenthesis
Algorithm
• Whenever an opening is encountered, PUSH()
on to stack
• Whenever a closing is encountered,
– If stack is empty, expression is invalid.
– If stack is nonempty, POP() the stack and check
with corresponding closing parenthesis. If match
occurs continue. Otherwise expression is invalid.
• When the end of expression is reached, stack
must be empty; otherwise expression invalid.
Symbol Stack
[ [
( [(
Example: A [(
+ [(
[(A+B)-{(C+D)-E}] B [(
) [
- [
{ [{
( [{(
C [{(
+ [{(
D [{(
) [{
- [{
E [{
} [
]
Algebraic Expression
• An algebraic expression is a legal combination of
operands and the operators.
• Operand is the quantity (unit of data) on which a
mathematical operation is performed.
• Operand may be a variable like x, y, z or a constant like
5, 4,0,9,1 etc.
• Operator is a symbol which signifies a mathematical or
logical operation between the operands. Example of
familiar operators include +,-,*, /, ^ , %
• Considering these definitions of operands and
operators now we can write an example of expression
as
x+y*z
Infix, Postfix and Prefix Expressions
• INFIX: From our schools times we have been familiar with the
expressions in which operands surround the operator, e.g.
x+y, 6*3 etc this way of writing the Expressions is called infix
notation.
Delimiters
• Sub expression within delimiters is treated as a
single operand, independent from the remainder
of the expression.
– (a + b) * (c – d) / (e – f)
WHY PREFIX and POSTFIX ?
623+-382/+*2^3+)
5
6
65-382/+*2^3+) 1382/+*2^3+)
8 2 4
3 3 8 3
1 1 1 3 1
1
Cont. of Evaluation- 623+-382/+*2^3+
134+*2^3+)
4
3 7
1 1
72^3+) 493+) )
2 3
7 7 49
= 52 49 52
Algorithm: To evaluate a prefix value