Title: Training
1Basic Data TypesQueues
Richard Newman Based on Sedgewick and Wayne
2Stacks and Queues
- Stacks
- Dynamic Resizing
- Queues
- Generics
- Iterators
- Applications
3Fundamental data types
Values sets of objects
Operations insert, remove, test if
empty. Intent is clear when we insert. Which
item do we remove?
4Fundamental data types
Stack Remove the item most recently
added. (LIFO last in first out) Analogy
Cafeteria trays. Web surfing. Queue Remove the
item least recently added. (FIFO first in
first out) Analogy Grocery store checkout line.
5Queue API
Public class Queue Can be any type (stay
tuned) Queue ( ) Create an empty queue Void
enqueue (String S) Insert a new item onto
stack String dequeue ( ) Remove and return
the item least recently added Boolean isEmpty
( ) Is the queue empty?
ENQUEUE
DEQUEUE
NEWEST
OLDEST
6Queue linked-list implementation
Can it be done with a singly linked list? a) No
not efficiently b) c) d) IDK
Most recent
Least recent
of
best
the
was
it
Most recent
Least recent
of
best
the
was
it
7Dequeue linked-list implementation
tail
head
of
best
the
was
it
String item head.item
it
tail
head
of
best
the
was
it
head head.next
tail
head
of
best
the
was
return item
it
8Enqueue linked-list implementation
tail
oldTail
head
best
the
was
it
Node oldTail tail
tail
oldTail
head
of
best
the
was
it
tail new Node() tail.item of
tail
oldTail
head
of
best
the
was
it
oldTail.next tail
9Queues array implementation
Use array q to store items in
queue enqueue() add new item at
qtail dequeue() remove item from
qhead Update (increment) head and tail
modulo capacity
of
best
the
was
it
q
0 head
1
2
3
4
5 tail
10Queues array implementation
enqueue() add new item at qtail
q
of
best
the
was
it
times
1
2
3
4
5
6
0
head
tail
11Queues array implementation
dequeue() remove item from qhead
of
best
the
was
it
q
times
1
2
3
4
5
6
0
head
tail
12Queues array implementation
Update (increment) head and tail modulo capacity
(7)
of
best
the
was
q
times
it
was
1
2
3
4
5
6
0
head
tail
13Dynamic ResizingQueues array implementation
Arrays are instantiated with a specific size Q
How to grow queue when capacity reached? Q When
to shrink array when queue shrinks? A What do
you think? )
14Next Generics