Download presentation
Presentation is loading. Please wait.
1
Basic Data Types Queues
Richard Newman Based on Sedgewick and Wayne 1
2
Stacks and Queues Stacks Dynamic Resizing Queues Generics Iterators
Applications 2
3
Fundamental data types
• Values: sets of objects • Operations: insert, remove, test if empty. • Intent is clear when we insert. • Which item do we remove? 3
4
Fundamental 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. 4
5
Queue API Public class Queue: Can be any type (stay tuned) ENQUEUE
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 5
6
Queue: 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
7
Dequeue: 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”
8
Enqueue: 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;
9
Queues: array implementation
Use array q[ ] to store items in queue enqueue() add new item at q[++tail] dequeue() remove item from q[head++] Update (increment) head and tail modulo capacity q[] it was the best of head 1 2 3 4 5 tail
10
Queues: array implementation
enqueue() add new item at q[++tail] q[] it was the best of times 1 2 3 4 5 6 head tail
11
Queues: array implementation
dequeue() remove item from q[head++] q[] it was the best of times 1 2 3 4 5 6 head tail
12
Queues: array implementation
Update (increment) head and tail modulo capacity (7) q[] was was the best of times it 1 2 3 4 5 6 head tail
13
Dynamic Resizing Queues: 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? :)
14
Next: Generics
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.