2/39
Part 1 of 7 · Nodes and costsLearn and do

A list is nodes joined by pointers

Python has no linked list type, and interviewers know it. When a question is about one, it hands you a small class for the nodes, and the question is about the pointers between them.

class Node:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next


def values(head):
    out, node = [], head
    while node is not None:
        out.append(node.val)
        node = node.next
    return out


head = Node(3, Node(1, Node(4)))
print(values(head))
[3, 1, 4]

In memory, that list is three separate objects, each pointing at the next:

Three nodes in memory
3head
→
1
→
4
→None

Three separate objects. Each holds a value and a pointer to the next node, and the last one points at None.

A node holds a value and a pointer, next: a reference to the node after it, or None at the end. The list is known by its first node, the head. None is the empty list.

There's no length and no index. To reach anything, you start at the head and follow next, the way values does.

values tests node, not node.next. Test node.next and the walk stops one node early:

def values_wrong(head):
    out, node = [], head
    while node.next is not None:
        out.append(node.val)
        node = node.next
    return out


print(values_wrong(head))
[3, 1]

On the empty list it's worse: node is None, and None.next raises AttributeError: 'NoneType' object has no attribute 'next'.

In the editor, write length(head). It prints the length of a three-node list and of the empty list.