7 - 1 Stacks and Queues
7 - 1 Stacks and Queues
7 - 1 Stacks and Queues
top
[ A+ { B - C + (D + E) } ]
Stack in Action ….
top
Push( ‘[‘ ); [
[ A+ { B - C + (D + E) } ]
Stack in Action ….
top
{
Push( ‘{‘ ); [
[ A+ { B - C + (D + E) } ]
Stack in Action ….
top
(
{
Push( ‘(‘ ); [
[ A+ { B - C + ( D + E) } ]
Stack in Action ….
top
(
{
Pop( ); [
[ A+ { B - C + ( D + E ) } ]
Stack in Action ….
top
{
[
[ A+ { B - C + (D + E) } ]
Stack in Action ….
top
{
Pop( ); [
[ A+ { B - C + (D + E) } ]
Stack in Action ….
top
[
[ A+ { B - C + (D + E) } ]
Stack in Action ….
top
Pop( ); [
[ A+ { B - C + (D + E) } ]
Stack in Action ….
top
[ A+ { B - C + (D + E) } ]
Postfix Expression
5 7 + 6 2 - * top
Stack in Action ….
Postfix Expression
top
5
5 7 + 6 2 - *
Stack in Action ….
+ 6 2 - * 5
5 7
Stack in Action ….
+ 6 2 - * 5
5 7 top
Postfix Expression
top
12
5 7 + 6 2 - *
Stack in Action ….
top
Postfix Expression 6
12
5 7 + 6 2 - *
Stack in Action ….
top
2
Postfix Expression 6
12
5 7 + 6 2 - *
Stack in Action ….
top
2
top
Postfix Expression 6 4
12 12
5 7 + 6 2 - *
Result = Pop( ) “-” Pop( ) Push (Result)
Stack in Action ….
top
Postfix Expression 4
12
5 7 + 6 2 - *
Postfix Expression top
4
top
5 7 + 6 2 - * 12 48
5 7 + 6 2 - * Result = Pop( )
Result = 48
Evaluation of Postfix
•
Expression
Evaluation of infix Expression is difficult because :
– Rules governing the precedence of operators are to be
catered for
– Many possibilities for incoming characters
– To cater for parentheses
– To cater for error conditions / checks
• Evaluation of postfix expression is very simple to implement
because operators appear in precisely the order in which they
are to be executed
Motivation for the
conversion
• Motivation for this conversion is the need to have the
operators in the precise order for execution
• While using paper and pencil to do the conversion we
can “foresee” the expression string and the depth of all
the scopes (if the expressions are not very long and
complicated)
• When a program is required to evaluate an expression, it
must be accurate
• At any time during scanning of an expression we cannot
be sure that we have reached the inner most scope
• Encountering an operator or parentheses may require
frequent “backtracking”
• Rather than backtracking, we use the stack to
“remember” the operators encountered previously
Assignment # 1
• Write a program that gets an Infix arithmetic
expression and converts it into postfix notation
• The program should then evaluate the postfix
expression and output the result
• Your program should define the input and output
format, enforce the format and handle Exceptions
(exceptional conditions).
• Use appropriate comments at every stage of
programming