Kodewick
Start learning →
Linked lists: nodes and next9 / 52

Linked lists: nodes and next

Lesson 9 of 52 · Part 2 · Names, lists and linked lists · about 15 minutes

A linked list keeps each value in a node object whose next points at the following node; you walk it from head with while cur until None, adding at the front is O(1), but reaching item i takes i steps.

Lesson 2 worked it out: inserting at the front of a list 100,000 times moves about 5 billion items, because the slots must stay side by side. A linked list stores things differently: each value lives in a node object of its own, the nodes are scattered around memory, and each one points at the next through next. Adding one at the front means making one node and changing one reference, whether the list has 10 nodes or 100,000. The price is that there is no a[i] any more: to get item i, you walk i steps from the front.

A node: a value plus next

A node is a tiny object: val holds the value, next points at the next node, and the last one's next is None. The whole list only needs to remember the first node, called the head. This is lesson 1's "reference" again: next is just a name on a node object, pointing at another object. Press play and step through it:

class Node:    def __init__(self, val, next=None):        self.val = val        self.next = next c = Node(9)b = Node(7, c)a = Node(3, b)head = aprint(head.val, head.next.val, head.next.next.val)print(head.next.next.next)
Three nodes made back to front: each next points at the one after it; head remembers the first, and following next reaches them all

head.next.next.next is the next of the last node, 9, which is None. The names a, b and c only made building it easier; the list itself is held together by next alone:

main.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6head = Node(3, Node(7, Node(9)))7second = head.next8print(second.val, second.next.val)9print(head.next is second)
Output
7 9
True
Choose one

What is the next of the last node in a linked list?

Guess the outputA wrong guess is fine

What does this print?

1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6head = Node(3, Node(7, Node(9)))7print(head.next.next.val - head.next.val)
Put in orderDrag, or use the arrows

Put the three lines that make the nodes in order so the program prints 3 7 9. When you make a node, the node its next points at must already exist.

  1. b = Node(7, c)
  2. a = Node(3, b)
  3. c = Node(9)
Should print
3 7 9

Walking it: while cur

Walking a linked list is nearly always these three lines:

head↓cur↓
3a
7b
9c
None
1cur = head2while cur:3    print(cur.val)4    cur = cur.next

cur starts at head, prints one each turn, then cur = cur.next; at None, while cur stops

Why use a separate cur instead of moving head? Once head moves on, nothing refers to the nodes before it: part of the list is lost, and Python reclaims those nodes.

main.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6head = Node(3, Node(7, Node(9)))7 8cur = head9while cur:10    print(cur.val, end=" ")11    cur = cur.next12print()13 14total, count = 0, 015cur = head16while cur:17    total += cur.val18    count += 119    cur = cur.next20print("sum", total, "count", count)21print(head.val)
Output
3 7 9 
sum 19 count 3
3
Guess the outputA wrong guess is fine

The condition is now while cur.next. What does it print?

1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6head = Node(3, Node(7, Node(9)))7cur = head8count = 09while cur.next:10    count += 111    cur = cur.next12print(count, cur.val)
Fill inTap one to fill a blank; tap a blank to take it back

Pick what goes in the blank so cur moves along one node at a time and adds up 3 + 7 + 9.

1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6head = Node(3, Node(7, Node(9)))7total = 08cur = head9while cur:10    total += cur.val11    cur = 12print(total)
Exercise 1

Where is it?

Finish find(head, x): return the position (counting from 0) where the value x first appears, or -1 if it is not there.

It should print
0 1 2 -1
-1
exercise1.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6def find(head, x):7    # cur walks from head, i counts along8    return -19 10head = Node(3, Node(7, Node(9, Node(7))))11print(find(head, 3), find(head, 7), find(head, 9), find(head, 5))12print(find(None, 3))
Output
Press Run or Ctrl+Enter

A list class: __iter__ and __len__

Wrap the head in a class and give it two special methods, and it works with for, list() and len() just like a list:

  • __iter__ written as a generator: the function has a yield, and each time a value is asked for, it runs on to the next yield, hands over cur.val, and picks up from there next time.
  • __len__ returns the size it keeps: add 1 for every node added, and len(L) is O(1) instead of a walk every time.

Adding one at the front (push_front) changes a single reference:

head↓
1d
3a
7b
9c
None

push_front(1): the new node's next points at the old first node, then head points at the new node; one reference changed
main.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6class LinkedList:7    def __init__(self):8        self.head = None9        self.size = 010 11    def push_front(self, val):12        self.head = Node(val, self.head)13        self.size += 114 15    def __iter__(self):16        cur = self.head17        while cur:18            yield cur.val19            cur = cur.next20 21    def __len__(self):22        return self.size23 24L = LinkedList()25for x in [9, 7, 3, 1]:26    L.push_front(x)27print(list(L), len(L))28for v in L:29    print(v, end=" ")30print()31print(sum(L), max(L), 7 in L, 8 in L)
Output
[1, 3, 7, 9] 4
1 3 7 9 
20 9 True False

With __iter__ in place, sum, max and in all just work. But every one of them walks from head: 7 in L is O(n).

Guess the outputA wrong guess is fine

After three calls to push_front, what does this print?

1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6class LinkedList:7    def __init__(self):8        self.head = None9        self.size = 010 11    def push_front(self, val):12        self.head = Node(val, self.head)13        self.size += 114 15    def __iter__(self):16        cur = self.head17        while cur:18            yield cur.val19            cur = cur.next20 21    def __len__(self):22        return self.size23 24L = LinkedList()25for x in [1, 2, 3]:26    L.push_front(x)27print(list(L), len(L))

The price: no a[i]

Operationlistlinked list (head only)
Get item iO(1)O(i): walk i steps from the front
Add at the frontO(n): everything moves backO(1): change one reference
Add at the endamortised O(1)O(n) to walk to the end; O(1) if you also keep a tail
lenO(1)O(n) to walk it; O(1) if you keep a size
x in …O(n)O(n)
Extra per itemone referencea node object: two references, val and next, plus the object's own overhead

A linked list has one strength: when you already hold a node, inserting and deleting next to it is O(1) (next lesson). Almost everywhere else a list does better.

In interviews: linked-list problems always give you class ListNode: def __init__(self, val=0, next=None) and just the head. Draw a few nodes and arrows on paper first, then write while cur; think hard about both ends: the empty list (head is None) and the last node.

Choose one

The list is head → 5 → 1 → 4 → 2. cur starts at head (on 5). How many times do you run cur = cur.next to land on 4?

Choose allPick all that apply

The list only keeps head: no size and no tail. Which of these are O(n)? (You can pick more than one.)

Exercise 2

Keep a tail, and adding at the end is O(1) too

Finish append(val) for LinkedList: self.tail remembers the last node, so attach a new node after it without walking from the front. In an empty list, both head and tail must point at the new node.

It should print
[3, 7, 9] 3
3 9 None
exercise2.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6class LinkedList:7    def __init__(self):8        self.head = None9        self.tail = None10        self.size = 011 12    def append(self, val):13        # empty list: head and tail are both the new node; otherwise attach after tail and move tail on14        pass15 16    def __iter__(self):17        cur = self.head18        while cur:19            yield cur.val20            cur = cur.next21 22    def __len__(self):23        return self.size24 25L = LinkedList()26for x in [3, 7, 9]:27    L.append(x)28print(list(L), len(L))29print(L.head.val, L.tail.val, L.tail.next)
Output
Press Run or Ctrl+Enter

How you write it at work

Python's standard library has no singly linked list type, and you will rarely write one at work: use a list when things go in and out at the end, and collections.deque for both ends (in CPython it is a doubly linked chain of 64-slot blocks: O(1) at both ends, O(n) to index into the middle). Linked lists turn up mainly in interview problems and inside other structures: an LRU cache (lesson 6), a hash table's chains, a graph's adjacency lists.

For practice problems, write two small helpers first, one to build a linked list from a list and one to turn it back into a list for printing. They save a lot of debugging:

main.py
1class ListNode:2    def __init__(self, val=0, next=None):3        self.val = val4        self.next = next5 6def from_list(vals):7    head = None8    for v in reversed(vals):9        head = ListNode(v, head)10    return head11 12def to_list(head):13    out = []14    while head:              # head is just this function's name: moving it changes nothing outside15        out.append(head.val)16        head = head.next17    return out18 19h = from_list([1, 2, 3, 4])20print(to_list(h))21print(to_list(from_list([])))22print(h.val)
Output
[1, 2, 3, 4]
[]
1
Choose one

How fast is collections.deque at adding and removing at both ends, and at getting an item in the middle by index?

Summary

Take-away

A linked list: each node points at the next

  • Node = val + next; the last one's next is None; head remembers the first
  • Walk with a separate cur: while cur handles each node, while cur.next stops on the last
  • Adding at the front changes one reference: O(1); getting item i walks i steps: O(n)
  • __iter__ is a generator with yield; __len__ returns the size you keep
1cur = head2while cur:3    print(cur.val)4    cur = cur.next5self.head = Node(val, self.head)   # push_front