DS-Chapter - 3
DS-Chapter - 3
Data Structure
What is a Stack
Stack Operations
Push Operation
Pop Operation
stack
A stack is a
Last In, First
Out (LIFO) data
structure,
objects
inserted last
are the first to
come out of
the stack.
What is a stack?
E top
D top D D
C top C C C
B top B B B B
A top A A A A A
Operation
Performed on
Stack
Push: add an element in stack
Pop: remove an element in stack
A LIFO Stack
Push Pop
Bottom
Array-based Stack Implementation
Allocate an array of some size (pre-defined)
Maximum N elements in stack
Bottom stack element stored at element 0
last index in the array is the top
Increment top when one element is pushed,
decrement after pop
Stack implementation
Stacks
Push X w y x
Pop w y
1.Display(top,i,a[i])
2.If top=0 then
Print ‘STACK EMPTY’
Exit
Else
3.For i=0 to top
Print a[i]
End for
4.exit
Data Structures: A Pseudocode Approach with 22
Stack Applications
Real life
Pile of books
Plate trays
More applications related to computer
science
Evaluating expressions
APPLICATIONS OF STACKS ARE:
I. Reversing Strings:
• A simple application of stack is reversing strings.
To reverse a string , the characters of string are
pushed onto the stack one by one as the string
is read from left to right.
• Once all the characters
of string are pushed onto stack, they are
popped one by one. Since the character last
pushed in comes out first, subsequent pop
operation results in the reversal of the string.
For example:
To reverse the string ‘REVERSE’ the string is
read from left to right and its characters are
pushed . LIKE:
onto a stack.
II. Checking the validity of an expression
containing nested parenthesis:
INFIX notation:
The general way of writing arithmetic expressions is known as infix notation.
e.g, (a+b)
PREFIX notation:
e.g, +AB
POSTFIX notation:
e.g: AB+
( (AB+)*C-(DE-) ) $ (FG+)
( (AB+C*)-(DE-) ) $ (FG+)
(AB+C*DE--) $ (FG+)
AB+C*DE- -FG+$
Infix to Postfix
Example-1: A+B*C
( (A-(B+C) ) *D ) $ (E+F)
A trace of the algorithm that converts the infix expression
a - (b + c * d)/e to postfix form