Fundamental Data Structures
Data structures make heavy use of pointers and dynamically allocated memory.
Stacks & Queues
ATD: Abstract Data Types
| ADT |
data structures |
| list of supported operations |
specify exactly |
| how data is represented |
| what should happen |
algorithms for operations |
| not: how to do it |
has concrete costs |
| (space and running time) |
| not: how to store data |
|
Stack
- Operators
- top(): Return the topmost item on the stack Does not modify the stack.
- push(x): Add π₯ onto the top of the stack.
- pop(): Remove the topmost item from the stack (and return it).
Queue
- Operators:
- enqueue(x): Add π₯ at the end of the queue.
- dequeue(): Remove item at the front of the queue and return it.
Resizable Arrays (ε―εε€§ε°ηζ°η»)
// Digression ι’ε€θ―
- Array operations:
- create(n)
- get(i)
- set(i, x)
Arrays have fixed size (supplied at creation).
Doubling trick
maintain capacity πΆ = π.length so that 14 πΆ β€ π β€ πΆ
Amortized Analysis (ζιεζ)
Formally: consider βcredits/potentialβ Ξ¦ = min{π β 14 πΆ, πΆ β π} β [0, 0.6π]
amortized cost of an operation = actual cost (array accesses) β 4 Β· change in Ξ¦
- cheap push/pop: actual cost 1 array access, consumes β€ 1 credits β amortized cost β€ 5
- copying push: actual cost 2π + 1 array accesses, creates 21 π + 1 credits β amortized cost β€ 5
- copying pop: actual cost 2π + 1 array accesses, creates 12 π β 1 credits β amortized cost 5
- sequence of π operations: total actual cost β€ total amortized cost + final credits
- here: β€ 5π + 4Β·0.6π = Ξ(π+π)
Priority Queues & Binary Heaps
Priority Queue ADT
elements in the bag have different priorities.
-
Operators:
- construct(π΄): Construct from from elements in array π΄.
- insert(π₯,π): Insert item π₯ with priority π into PQ.
- max(): Return item with largest priority. (Does not modify the PQ.)
- delMax(): Remove the item with largest priority and return it.
- changeKey(π₯,πβ²): Update π₯βs priority to πβ². Sometimes restricted to increasing priority.
-
PQ implementations
- Elementary implementations
- unordered list β Ξ(1) insert, but Ξ(π) delMax
- sorted list β Ξ(1) delMax, but Ξ(π) insert

Why heap-shaped trees(ε ε½’ζ )?
Operations on Binary Heaps
Insert
-
Add new element at only possible place: bottom-most level, next free spot.
-
Let element swim up(ζΈΈδΈ) to repair heap order.
Delete Max
- Remove max (must be in root).
- Move last element (bottom-most, rightmost) into root.
- Let root key sink in(ζ²ε
₯) heap to repair heap order.
Heap construction
Binary heap summary
| Operation |
Running Time |
| construct(π΄[1β¦π]) |
π(π) |
| max() |
π (1) |
| insert(π₯,π) |
π(log π) |
| delMax() |
π(log π) |
| changeKey(π₯,πβ²) |
π(log π) |
| isEmpty() |
π (1) |
| size() |
π (1) |