Sei sulla pagina 1di 2

Applications of stack

Stack is used where LIFO (Last In First Out) is required.


Ex: 1) Reversing a given line
Ex: 2) Another application is in the conversion of arithmetic expressions
in high level language into machine readable form. (ie, infix
notation to postfix notation)
Ex:3) Evaluation of postfix notation using stack.

Polish string
Complex arithmetic operations can be converted into polish strings using
stack which then can be executed in two operands and one operator
form.
Polish Notation refers to the notation in which the operator symbol is
placed before the operands (prefix notation) or after its operands
(Reverse Polish Notation- Postfix Notation) in contrast to usual form
where operator is placed between the operands (infix notation).
Ex:
Polish Notation(Prefix)
+AB

Infix Notation
A+B

Reverse Polish Notation(Postfix)


AB+

Advantages of Postfix expression over Infix Expressions


An infix expression is difficult for machine to know and keep track of
precedence of operators. On other hand, a postfix expression itself
determines the precedence of operators (as the placement of operators in
a postfix expression depends upon its precedence). Therefore, for
machine it is easier to carry out a postfix expression than an infix
expression.

Algorithm to convert Infix Notation to Postfix Notation


The following algorithm converts an infix expression X into its
equivalent postfix expression Y. The algorithm uses a stack to
temporarily hold the operators and left parenthesis.
Suppose X is an arithmetic expression written in infix notation. This
algorithm finds the equivalent postfix expression Y.
Step 1: Push ( onto Stack, and add ) to the end of X.
Step 2: Scan X from left to right and Repeat steps 3 to 6 for each
element of X Until the Stack is empty.
Step 3: If an operand is encountered, add it to Y.
Step 4: If a left parenthesis is encountered, push it onto Stack.
Step 5: If an operator is encountered, then:
(a) Repeatedly pop from the Stack and add to Y each operator
which has the same precedence as or higher precedence than
operator.
(b) Add operator to Stack
Step 6: If a right parenthesis is encountered, then:
(a) Repeatedly pop from Stack and add to Y each operator
until a left
parenthesis is encountered.
(b) Remove the left parenthesis. (DO NOT add the left
parenthesis to Y)
Step 7: End.

************

Potrebbero piacerti anche