Download presentation
Presentation is loading. Please wait.
Published byCory Dickerson Modified over 9 years ago
1
CS 261- Winter 2009 Dynamic Array Queue and Deque
2
Dynamic Array Review Last lecture we introduced the dynamic array Benefits: Can be randomly accessed just like an array, grows as needed End user unaware of memory management issues (buffer reallocation when more space is needed)
3
you can build a Stack with a dynamic array Stack is easy with a dynamic array (add and remove elements from top end) Only complication is occasional buffer increase So O(1) remove, O(n) worst case insertion, but O(1) expected Latter often written as O(1)+
4
You can build a Bag with a dynamic array Building a bag is only slightly more complicated. Since order is unimportant, adding to end is easy Remove requires moving everything above the location down Add O(1)+, test: O(n), remove: O(n)
5
Picture of removal
6
What about building a queue? Recall queue is a collection where elements are inserted at one end, removed from another (think of queue of people waiting at a door) Which end makes most sense for insertion? For removal? What would be the O(?) ?
7
Removing from front
8
Inserting to front
9
What about a Deque Actually, easier to generalize the structure in this case to a Deque Deque - Double Ended Queue (or maybe Double Ended Staque…) Allows (efficient) insertions at both front and back Lets see how we can do this
10
Key idea Key idea: Don’t tie “front” to location zero Instead, allow both “front” and “back” to float around the array
11
Picture of array
12
Adding to either end Add to front - back off starting point by one Add to back - increase size by one Remove just the opposite There is just one small problem, what if elements wrap around?
13
Picture of wrapping around
14
How to handle wrapping When making new index position, if less than zero add capacity to number If larger than capacity, subtract capacity from number If size reaches capacity, reallocate new buffer as before (I’ve done this for you in the worksheet).
15
Your turn Write the code for Dynamic Array Deque
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.