You are on page 1of 8

Stacks- representation

• A stack is an ordered collection of items, generally implemented with


only two principle operations, called Push and Pop.
• stack – new nodes can be added and removed only at the top
• Push adds an item to a stack
• Pop extracts the most recently pushed item from the stack
– similar to a pile of dishes
– last-in, first-out (LIFO)
– Bottom of stack indicated by a link member to null
– stores the popped value
Advanced Data Structures
 Stack
◦ a stack is dynamic data items in a linear order,
such that the item first "pushed" in is the last item
"popped" out. Think of stack as a stack of books,
you are only allowed to put a book on top of the
stack or take a book from top of the stack.

Item 2
pushed on Item 2
Item 1 stack popped
pushed off
Stack
on stack
empty
stack 2

1 1 1
POLISH NOTATIONS
 Infix, Prefix and Postfix

 If the operator is placed in between operand, it is called infix


notation Ex. A+B (A+B)*C A+(B*C)

 prefix notations – operators preceded the operands


 Ex. +AB
 (A+B)*C = [+AB]*C = *+ABC
 A+(B*C) = A+[*BC) = +A*BC
 (A+B)/(C-D)= [+AB]/[-CD] = /+AB-CD

 Postfix- Operator symbol is placed after two operands


 Ex. A+B= AB+
 (A+B)*C= [AB+]*C= AB+C*
 A+(B*C) = A+[BC*]=ABC*+
Exercises
 A$B*C-D+E/F/(G+H)
 ((A+B)*C-(D-E))$(F+G)
 A-B/(C*D$E)
 (A+B$D)/(E-F)+G
 A*(B+D)/E-f*(G+H/K)
Evaluation

of Expressions
Consider the following infix expression
 A+(B*C-(D/E$F)*G)*H

 Convert into Postfix using Stack


 A +(B* C –(D/E $ F)*G) *H
Infix to Postfix : A+(B*C-(D/E$F)*G)*H
A ( A

+ (+ A

( (+( A

B (+( AB

* (+(* AB

C (+(* ABC

- (+(- ABC*

( ( + (- ( ABC*

D (+(-( ABC*D

/ (+(-(/ ABC*D

E (+(-(/ ABC*DE

$ ( + (- ( /$ ABC*DE

F (+(-(/$ ABC*DEF

) (+(- ABC*DEF$/

* (+(-* ABC*DEF$/G

G (+(-* ABC*DEF$/G* -

) (+ ABC*DEF$/G* -

* (+* ABC*DEF$/G* -H

H (+* ABC*DEF$/G* -H*+


EXERCISE
 623+-382/+*2$3+

symb op1 Op2 value Stack value

6 6
2 62
3 2 3 5 623
+ 6 5 1 65
- 6 5 1 1
3 6 5 1 13
8 6 5 1 138
2 8 2 4 1382
/ 3 4 7 134
+ 1 7 7 17
* 1 7 7 7
2 7 2 49 72
$ 7 2 49 49
3 49 3 52 49 3
+ 52

You might also like