Beruflich Dokumente
Kultur Dokumente
15-121
Introduction to Data Structures
Ananda Gunawardena
12/27/2018 1
Stack and Heap
• A stack is a first-in-last-out structure
•Stacks retain
Information
About where to
return
12/27/2018 3
A Stack interface
12/27/2018 4
Stacks are LIFO
Push operations:
b
a
12/27/2018 5
Stacks are LIFO
Pop operation:
e
Last element
that was pushed
is the first to be
d popped.
c
b
a
12/27/2018 6
Queues
• Behavior
– add item only from the back (enqueue)
– remove items only from the front (dequeue)
• Many Applications
– printer queue
– network queues
– common resource sharing
• Queue Operations
– enqueue
– dequeue
– clear
– empty
12/27/2018 7
– full
A Queue interface
12/27/2018 8
Queues are FIFO
back front
k r q c m
12/27/2018 9
Queues are FIFO
Enqueue operation:
back front
y k r q c m
12/27/2018 10
Queues are FIFO
Enqueue operation:
back front
y k r q c m
12/27/2018 11
Queues are FIFO
Dequeue operation:
back front
y k r q c m
12/27/2018 12
Implementation
12/27/2018 13
Implementing stacks, 1
Linked representation.
All operations constant
c time, or O(1).
12/27/2018 14
Implementing stacks, 2
• An alternative is to use an array-based
representation.
a b c
top
j a What happens
when the stack
on the right
becomes empty?
i b
h c
g d
f e
12/27/2018 16
Implementing a Queue with an
array
12/27/2018 17
Applications
12/27/2018 18
Applications of Stacks
• Balancing Symbols
• Problem: Write a program that will check
the validity of a statement
• Eg: (2 + 3 ( 4 – 5 )) is valid
• (2 + 3 (4 – 5 ) is not valid
12/27/2018 19
Applications of Stacks ctd..
• Evaluating Postfix expressions
• Consider the expression
( 2+ 3*(5 – 2) + 3*2)
• How do we write a program to find the answer to the
above expression?
• Write the expression in postfix notation
2 3 5 2 -*+3 2*+
12/27/2018 20
Stack Application - Maze
• Think about a grid of rooms separated by walls.
• Each room can be given a name.
a b c d
Find a path
e f g h thru the
maze from a
i j k l to p.
12/27/2018
m n o p 21
Applications of Queue
• Breadth First Traversal
12/27/2018 22
Applications of Queue
• Snake Game
12/27/2018 23
Homework
• Read notes on recursion
• Think of more applications where a stack
or queue can be used
• Read the assignment on Mazes
12/27/2018 24