Professional Documents
Culture Documents
Introduction to Stacks
• A stack is a last-in-first-out (LIFO) data
structure
• Adding an item
– Referred to as pushing it onto the stack
• Removing an item
– Referred to as
popping it from
the stack
2
A Stack
• Definition:
– An ordered collection of data items
– Can be accessed at only one end (the top)
• Operations:
– construct a stack (usually empty)
– check if it is empty
– Push: add an element to the top
– Top: retrieve the top element
– Pop: remove the top element
3
STACKS
Algorithm:-1
PUSH(STACK,TOP,MAXSTK,ITEM)
POP(STACK,TOP,ITEM)
PUSH_LINKSTACK(INFO,LINK,TOP,AVAIL,ITEM)
1. //[Available Space?]
if AVAIL=NULL , then write OVERFLOW and EXIT
2. //[Remove first node from the avail list]
set NEW:=AVAIL and AVAIL:=LINK[AVAIL]
3. Set INFO[NEW]:=ITEM //[copies ITEM into new node]
4.Set LINK[NEW]:=TOP //[new node points to the original top node in stack]
5.Set TOP=NEW //[reset TOP to point to new node at the top of stack]
6.Exit
Algorithm:-4
POP_LINKSTACK(INFO,LINK,TOP,AVAIL,ITEM)
This procedure deletes the top element an ITEM into a linked stack and assign it to
the variable ITEM
This procedure deletes an element from a queue and assign it to the variable item
Example:
(5 * 3) + 2 & 5 * (3 + 2)
Polish Notation
Polish Notation: The Operator Symbol is placed before
its two operands.
Example: + A B, * C D, / P Q etc.
29
Advantage of Postfix notation
• You can easily evaluate a postfix expression in
a single scan from left to right with the help of
a stack (unlike evaluating infix expressions).
31
Infix to Postfix
A+(B*C–(D/E↑F)*G)*H
Symbol Scanned Stack Expression P
A ( A
+ ( + A
( ( + ( A
B ( + ( AB
* ( + ( * AB
C ( + ( * ABC
- ( + ( - ABC*
( ( + ( - ( ABC*
D ( + ( - ( ABC*D
/ ( + ( - ( / ABC*D
E ( + ( - ( / ABC*DE
↑ ( + ( - ( / ↑ ABC*DE
A+(B*C–(D/E↑F)*G)*H
Example:
2 3 4 + 5 6 - - *
2 3 4 + 5 6 - - *
2 7 5 6 - - *
2 7 5 6 - - *
2 7 -1 - *
2 7 -1 - * 2 8 * 2 8 * 16
35
Evaluation of Postfix (RPN) Expression (Algo.)
P is an arithmetic expression in Postfix Notation.
2. Scan P from left to right and Repeat Step 3 and 4 for each element of
P until the sentinel “)” is encountered.
1. If N = 1, then
a) Write BegEnd
b) Return
3. Write BegEnd
7. Return