Sub topic 1
How Arrays and Linked Lists Sit in Memory
Prerequisites
This chapter assumes you can:
- Write basic programs with variables, loops and functions.
- Read code that uses references or pointers. A reference is a value that tells you where another value lives in memory.
- Read simple Big-O notation, such as O(1) (constant time) and O(n) (time grows with the number of elements).
The examples use Python. Python's list is a dynamic array, so it stands in for the array side of the comparison.
Two ways to lay out a sequence
Both structures store an ordered sequence of values. They differ in where the elements sit in memory and how you find the next one.
- An array keeps its elements in one contiguous block. Neighbors in the sequence are neighbors in memory.
- A linked list keeps each element in its own node. A node holds a value and a reference to the next node. The nodes can be anywhere in memory.
Almost every cost difference in later chapters follows from this one choice.
Arrays: position becomes arithmetic
Suppose an array starts at address base and each element takes size bytes. Element i then lives at:
address(i) = base + i * sizeThe computer does one multiplication and one addition. It does not look at any other element. This is why reading items[i] costs O(1) no matter how large the array is.
The layout also fixes the array's shape. The block has a set capacity, and the elements must stay packed together. Later chapters show what this means for insertion, deletion and growth.
Linked lists: position becomes a chain
A node stores a value and a reference to the next node. The list itself usually stores only a reference to the first node, called the head. The last node's next is None, which marks the end.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
head = Node(10, Node(20, Node(30)))
node = head
while node is not None:
print(node.value)
node = node.nextThis prints 10, 20 and 30. The code has no formula for the address of the third node. The only way to find it is to start at head and follow next twice. Each link you follow is one hop.
The allocator, the part of the runtime that hands out memory, may place each node wherever it finds free space. The links hold the order, so the nodes do not need to be next to each other.
Comparing the two layouts
| Property | Array | Linked list |
|---|---|---|
| Where elements live | One contiguous block | Separate nodes, scattered |
| What defines the order | Position in the block | `next` references |
| Finding element `i` | Compute an address | Follow `i` links |
| Extra data per element | None | At least one reference |
| Growing | Needs spare room or a new block | Allocate one node |
Seeing the difference in code
This example shows both access patterns. The array reaches index 2 directly. The linked list reaches it by following 2 links.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def get(head, index):
node = head
for _ in range(index):
if node is None:
break
node = node.next
if node is None:
raise IndexError(index)
return node.value
head = Node(10, Node(20, Node(30)))
print(get(head, 2)) # 30, reached by following 2 links
items = [10, 20, 30]
print(items[2]) # 30, reached by direct index arithmeticCommon mistakes
- Assuming a linked list is faster because it is "more flexible." Flexible layout does not make every operation cheaper. Reaching a position by index costs O(n).
- Assuming nodes are adjacent in memory. They may happen to be, but the structure gives no guarantee, so you cannot rely on it.
- Forgetting that the head is the only entry point. If you lose the reference to the head, you lose the whole list.
Exercise
An array starts at address 1000 and each element takes 8 bytes. At what address does element 5 live? Why can the computer find it without looking at elements 0 to 4, while a linked list cannot find its sixth node that way?
Show answer
The address is 1000 + 5 * 8 = 1040. Contiguous storage with a fixed element size lets the computer compute the address directly. In a linked list the nodes can be anywhere, so the address of the sixth node is stored only in the fifth node's next reference. You must follow the chain from the head to learn it.
Exercise
A linked list has 1,000 nodes and you only hold a reference to its head. How many link hops does it take to reach the last node?
Show answer
999 hops. The last node is at index 999, and reaching index i takes i hops from the head.