What is a linked list?
- Algorithms course
- Beginner
- Lesson 57/80
- 4 min
Nodes link to the next node with a pointer.
What is a linked list?
A linked list is a data structure where each node contains data and a pointer to the next node. Elements are not contiguous in memory.
Access in a linked list is O(n) because you must traverse from the start. However, insertion and deletion are O(1) (at the head).
Node definition
A node has two fields: data (the value) and next (pointer to the next node). The last node's next is None.
Nodes are linked to form a chain. The first node is the head and the whole list is accessed from there.
Practice Create node
Write make_node(data). Return {'data': data, 'next': None}. Print 5 with print(make_node(5)['data']).
Starter code
def make_node(data):
# Create nodeSample solution
def make_node(data):
# Create node
return {'data': data, 'next': None}
print(make_node(5)['data'])Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How are elements in a linked list in memory?
- In a matrix
- Scattered, linked by pointers Correct answer
- Sorted
- Contiguous
Explanation: Scattered, linked by pointers.
2 Node field
The node's next pointer is ____.
The node's next pointer is next.
Explanation: next is right.
3 What is a linked list: match the terms
| Term | Meaning |
|---|---|
Node |
data + next |
head |
First node |
next |
Pointer |
None |
Last node |