Module 5 · Stacks, Queues and Linked Lists · Lesson 17 of 40
Linked lists
A chain of nodes, each pointing to the next. Cheap to insert at the front, slow to reach the middle.
In this lesson · about 24 minutes
- Describe a node, the head and the tail
- Walk a linked list and insert at the head
- Compare a linked list with a Python list
A linked list is a chain. Each link is a node that holds two things: a value, and an arrow called next that points to the following node. The first node is the head. The last node is the tail; its next is None.
Unlike a Python list, the nodes do not sit side by side in memory. They can be anywhere, joined only by their arrows.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
head = Node(10, Node(20, Node(30))) # 10 → 20 → 30 → None
Walking the list
To visit every node, start at the head and follow the arrows until you reach None:
node = head
while node is not None:
print(node.value)
node = node.next
Good at, bad at
| Job | Linked list | Python list |
|---|---|---|
| Insert or delete at the front | O(1): just change arrows | O(n): everything shifts |
| Read item number i | O(n): walk from the head | O(1): jump straight there |
| Insert at the end | O(n), or O(1) if you keep a tail pointer | O(1) |
| Search for a value | O(n) | O(n) |
Try it · see it work
Linked list playground
Insert at the head, insert at the tail, and delete a value. Read how many steps each one takes.
Each box is a node: a value plus an arrow (next) to the following node.
Try it: build and walk a chain
Exercise
Count the nodes
A Node class is ready for you (with .value and .next). Write length(head) that returns how many nodes are in the list. An empty list has head = None.
Code that runs before yours
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def build(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def to_list(head):
out = []
while head is not None:
out.append(head.value)
head = head.next
return out
Exercise
Insert at the head
Write push_front(head, value) that makes a new node holding value, links it in front of the old head, and returns the new head.
Code that runs before yours
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def build(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def to_list(head):
out = []
while head is not None:
out.append(head.value)
head = head.next
return out
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.