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.
- right answers
- arguments left as they should be
Already written for you — you can use these
1class Node:2def __init__(self, value, next=None):3self.value = value4self.next = next56def build(values):7head = None8for v in reversed(values):9head = Node(v, head)10return 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.