Linked lists: nodes and next
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)
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:
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)
7 9 True
What is the next of the last node in a linked list?
None means "nothing comes after", and that is how while cur knows when to stop. If the last node pointed back to the first, you would have a circular list, which is a different kind of list (lesson 6).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)
head.next is the node holding 7 and head.next.next is the one holding 9: 9 − 7 = 2. Every extra .next follows the reference one more step.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.
b = Node(7, c)a = Node(3, b)c = Node(9)
3 7 9
Node(7, c) needs c, so the node holding 9 has to be made first. Build from the back: 9 first, then 7, then 3. In the wrong order Python stops with a NameError: the name does not exist yet.Walking it: while cur
Walking a linked list is nearly always these three lines:
head↓cur↓1cur = head2while cur:3 print(cur.val)4 cur = cur.next
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.
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)
3 7 9 sum 19 count 3 3
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)
while cur.next only steps on while "there is a node after cur", so cur stops on the last node and never becomes None: from 3 to 7, then to 9, 2 steps, and cur.val is 9. When you want to attach a new node at the end, stopping on the last one is exactly what you need, so use while cur.next; to handle every node, use while cur.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)
cur = cur.next. The nodes are scattered around memory, so there is no "next slot" to work out.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.
0 1 2 -1 -1
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))
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 ayield, and each time a value is asked for, it runs on to the nextyield, hands overcur.val, and picks up from there next time.__len__returns thesizeit keeps: add 1 for every node added, andlen(L)is O(1) instead of a walk every time.
Adding one at the front (push_front) changes a single reference:
head↓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)
[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).
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))
len(L) calls __len__, which returns size, and size went up by 1 each time: 3.The price: no a[i]
| Operation | list | linked list (head only) |
|---|---|---|
| Get item i | O(1) | O(i): walk i steps from the front |
| Add at the front | O(n): everything moves back | O(1): change one reference |
| Add at the end | amortised O(1) | O(n) to walk to the end; O(1) if you also keep a tail |
len | O(1) | O(n) to walk it; O(1) if you keep a size |
x in … | O(n) | O(n) |
| Extra per item | one reference | a 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.
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?
a[i] on a list, which gets there in one.The list only keeps head: no size and no tail. Which of these are O(n)? (You can pick more than one.)
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.
[3, 7, 9] 3 3 9 None
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)
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:
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)
[1, 2, 3, 4] [] 1
How fast is collections.deque at adding and removing at both ends, and at getting an item in the middle by index?
d[i] has to count its way through the blocks, so the middle is O(n). If you need any index at random, use a list.Summary
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