Scroll to turn the page
Data Structures and Algorithms · Data Structures and Algorithms
arrays, linked lists, and two disciplines
A data structure is a way of arranging data in memory so that some operations are cheap. The two basic arrangements of a sequence are the array, one contiguous block, and the linked list, separate nodes that each point to the next.
The figure is a linked list, 10 → 20 → 30 → 40 → None. To insert 25 after 20, make a node, point it at 20’s successor, then point 20 at it:
node = Node(25) node.next = prev.next prev.next = node
Two pointers change, however long the list: O(1). The order of the two assignments matters: done the other way round, prev.next would already point at the new node and the rest of the list would be lost.
The chapter compares the two arrangements (2.1–2.3), then builds two restricted sequences on them: the stack (2.4) and the queue (2.5), and ends with how to choose (2.6).
one block: fast to index, slow to insert into
An array stores its elements side by side in one block of memory. Element i is at address base + i × size, so reaching any index is one multiplication and one addition: O(1) random access.
In the figure each value takes 8 bytes and the block starts at a hypothetical address 1000, so a[2] is at 1016 and a[5] at 1040. Being contiguous also makes arrays fast in practice: neighbors share cache lines.
def insert(a, size, index, x): for i in range(size, index, -1): a[i] = a[i - 1] # shift right a[index] = x return size + 1
The price is insertion. To put 99 at index 2, every element from there to the end moves one slot right, last first so nothing is overwritten: 4 moves here, giving [3, 8, 99, 13, 21, 34, 55]. Inserting at index i of n elements moves n − i of them, so inserting or deleting near the front is Θ(n). Appending at the end moves nothing.
When the block is full, a dynamic array allocates a block twice the size and copies (1.7), which keeps append O(1) amortized.
nodes and next pointers
A singly linked list is a chain of nodes. Each node holds a value and a next pointer to the following node; the last points to None. The list itself is just a pointer to the first node, the head.
def find(head, target): cur = head while cur is not None: if cur.value == target: return cur cur = cur.next return None
There is no address arithmetic: the only way to the k-th node is to follow k pointers from the head. Finding 18 in 12 → 7 → 31 → 18 → 5 → None visits 4 nodes. Access by position, and search, are Θ(n) in the worst case.
def push_front(head, x): node = Node(x) node.next = head return node # the new head
What a linked list does well is change shape. Pushing 4 on the front creates one node and moves head: O(1), with nothing shifted. Inserting after a node you already hold is O(1) too, as on this chapter’s first page. Each node costs memory for its pointer, and nodes scattered through memory are slower to walk than an array’s block.
the node before is the one that changes
To delete a node from a singly linked list, change the next pointer of the node before it to skip over it.
def remove(head, target): if head.value == target: return head.next prev = head while prev.next is not None: if prev.next.value == target: prev.next = prev.next.next return head prev = prev.next return head
Removing 23 from 6 → 15 → 23 → 42 → None: prev walks until prev.next holds 23, then prev.next = prev.next.next. Nothing points at the removed node any more, and Python’s garbage collector reclaims it. Deleting the head is a special case: the new head is head.next.
Two refinements remove most special cases:
Doubly linked lists. Each node also has a prev pointer. Given a node, it can unlink itself in O(1): node.prev.next = node.next and node.next.prev = node.prev, with no walk to find the node before. A tail pointer makes appending O(1) as well. Python’s collections.deque and Java’s LinkedList are doubly linked.
Sentinels. A dummy node before the first real one (and, in a doubly linked list, after the last) means every real node has a neighbor on each side, so inserting or deleting at the ends needs no special code.
last in, first out
A stack allows changes at one end only, the top: push adds an element there and pop removes the most recently pushed one. Last in, first out (LIFO). Both are O(1) on a dynamic array (push and pop at the end) or on a linked list (at the head).
def balanced(s): stack = [] pairs = {')': '(', ']': '[', '}': '{'} for ch in s: if ch in '([{': stack.append(ch) # push elif not stack or stack.pop() != pairs[ch]: return False return not stack Checking brackets is a stack’s classic job: an opener must be closed by the matching closer, most recent first. For "{[()()]}" each opener is pushed and each closer pops its partner; the stack is never deeper than 3 and ends empty, so it is balanced. "([)]" fails: ) arrives while [ is on top.
Stacks run every program: each function call pushes a frame holding its local variables and where to return, and returning pops it. That call stack is why recursion unwinds in reverse order. Undo histories and depth-first search (Chapter 6) are stacks too.
first in, first out, in a ring buffer
A queue adds at the back (enqueue) and removes from the front (dequeue): first in, first out (FIFO), like a line at a counter.
On a plain array, dequeuing from index 0 would shift everything left: Θ(n). A ring buffer (circular array) instead keeps a head index and a size, and lets the indices wrap around with %:
def enqueue(self, x): self.data[(self.head + self.size) % self.cap] = x self.size += 1 def dequeue(self): x = self.data[self.head] self.head = (self.head + 1) % self.cap self.size -= 1 return x
The figure runs enqueue 5, enqueue 9, enqueue 2, dequeue, dequeue, enqueue 7, enqueue 4, enqueue 8, dequeue, enqueue 6, dequeue on capacity 6. The values leave in the order they came, 5, 9, 2, 7, and the enqueue of 6 wraps around to slot 0 while slots 4 and 5 are in use. Both operations are O(1); when the buffer is full it can double, like a dynamic array.
A linked list with head and tail pointers is also an O(1) queue. A deque (double-ended queue) allows both operations at both ends. Queues schedule print jobs and network packets, and drive breadth-first search (Chapter 6).
the operations decide
An abstract data type says what operations a structure offers (a list, a stack, a queue); a data structure says how they are carried out. The same ADT can be built on either arrangement, and the costs differ:
| operation | dynamic array | linked list |
|---|---|---|
| get the i-th element | O(1) | O(i) |
| search for a value | O(n) | O(n) |
| insert or delete at the front | O(n) | O(1) |
| insert or delete at the back | O(1) amortized | O(1) with a tail (delete needs doubly linked) |
| insert or delete next to a node you hold | O(n) | O(1) |
| memory per element | the value (plus spare capacity) | the value and one or two pointers |
The figure prepends 1 to 5 to each. The array moves 0, 1, 2, … elements each time, 10 in all (n(n − 1)/2 for n prepends: quadratic). The linked list moves none.
In practice dynamic arrays win more often than the table suggests: their elements sit together in memory, which caches reward. Choose a linked list when the work is mostly splicing at known positions.