The available-space list
Keep a pool's free nodes in a linked list: getting a node takes one off its front and returning one puts it back in front; both O(1).
When a linked list's nodes come from a fixed-size pool (an array), we need to know which nodes are free. The free
nodes themselves are chained through their link field into an available-space list starting at avail:
- Time:
O(1) per operation - Space:
O(pool size) - Horowitz–Sahni, chapter 4
A positive number gets a node and −k returns node k. Node 2, once returned, is the first one handed out again.
def available_space(ops):# A pool of 6 nodes numbered 1..6; each row is [node, value, link], and link 0 means null.n = 6pool = [[i, "·", i + 1 if i < n else 0] for i in range(1, n + 1)]avail = 1used = []for op in ops:if op > 0:if avail == 0:continuenode = availavail = pool[node - 1][2]pool[node - 1][1] = oppool[node - 1][2] = "-"used.append(node)else:k = -opif k not in used:continueused.remove(k)pool[k - 1][1] = "·"pool[k - 1][2] = availavail = kreturn used
Start
The table is still empty.
Local variables
Orange = changed in this step
ops list
Call stack
- available_space()line 1
Explanation
The idea
When a linked list's nodes come from a fixed-size pool (an array), we need to know which nodes are free. The free
nodes themselves are chained through their link field into an available-space list starting at avail:
- get a node (
GetNode): take the first node of the free list;availmoves on; - return a node (
RetNode): put the node at the front of the free list.
Both are O(1); the free list behaves like a stack.
The input
A positive number means "get a node and store this number in it", and −k means "return node k". The pool has 6
nodes numbered 1 to 6, and a link of 0 means null.
What to watch in the trace
- The table is the pool: each node's value and
link. Read the free list fromavailby following the links.