Vous êtes sur la page 1sur 3

Applications of Stacks

1. Evaluation of Postfix Expression


2. Transforming Infix Expressions into Postfix Expressions

1. Evaluation of Postfix Expression


Algorithm:
Input: Given an arithmetic expression in Postfix notation.
Output: Value of the arithmetic expression
1. Array = (arithmetic expression)
2. For I -> 1 to Array.length
3. If (Array[ I ] = operand )
4. Push (Array[I])
5. Else if (Array[I] = operator)
6. A = Pop()
7. B = Pop()
8. Result= B (operator) A
9. Push(Result)
10. Value = Top()
11. Exit

Example:
Given: Arithmetic Postfix expression:
10 2 8 * + 3 -
2. Transforming Infix Expressions into Postfix Expressions
Algorithm:
Input: Given an arithmetic expression in Infix notation.
Output: Postfix notation of the given arithmetic expression is returned
1. Push(Stack, ( )
2. Add ) at the end of arithmetic expression
3. Array = (arithmetic expression)
4. For I -> 1 to Array.length
5. If (Array[I]=operand)
6. Add (Postfix_Exp, Array[I])
7. Else if (Array[I] = ()
8. Push(Stack, Array[I])
9. Else if (Array[I] = operator )
10. A=Pop(Stack)
11. While(A is operator & precedence(A) > = precedence (Array[I]) )
12. Add(Postfix_Exp, A)
13. A=Pop(Stack)
14. Push(Stack, A)
15. Push(Stack, Array[I])
16. Else if (Array[I] = ))
17. A=Pop(Stack)
18. While(A != ( )
19. Add(Postfix_Exp, A)
20. A=Pop(Stack)
21. Remove(A) // remove and do not add ( to Postfix_Exp
22. Exit
Example:
Given: Arithmetic Infix expression:
(30 + 20) * (60 20) / 8 + 10

Vous aimerez peut-être aussi