Skip to content

Linked lists · warm-up

Length of a linked list

A linked list is a chain of Nodes: each has a value and a next, and the last one's next is None. The list is given by its first node, head (or None if empty).

Write length(head) returning how many nodes there are. Node and build([1, 2, 3]) already exist.

Already written for you — you can use these
1class Node:
2 def __init__(self, value, next=None):
3 self.value = value
4 self.next = next
5
6def build(values):
7 head = None
8 for v in reversed(values):
9 head = Node(v, head)
10 return head

Run adds print(length(build([1, 2, 3]))) after your code, to try it.

Stuck on the idea rather than the code? The Linked lists lesson walks through it.