Lesson 1 of 3
Nodes and pointers
A linked list is a chain of nodes, each holding a value and a pointer to the next one. Walk it by following the pointers from node to node, reverse it by turning every pointer around, and build new lists, such as two sorted lists merged into one, behind a placeholder node.
Draw a linked list as nodes and arrows, and say which node each name points at
Walk a linked list with
cur = cur.nextand stop safely atNoneReverse a linked list in place with
prev,curandnxtBuild a new list behind a dummy head with a
tailnameMerge two sorted lists by always taking the smaller front node
You have pulled data from an API that pages its results with cursors. Each response holds a batch of rows and a cursor for the next page, and the last response has no cursor. You cannot ask for page 40 directly. You follow the cursors, one page at a time, until there are none left.
That chain of pages is a linked list. A Python list keeps its items in numbered slots, side by side. A linked list keeps each item in its own small object, and each object knows only where the next one is. Linked list problems are short, but almost every line moves an arrow, and one move in the wrong order loses the rest of the list. So in this lesson the trace draws every node and every arrow.
A node and its pointer
What is a linked list, in Python?
A node is a small object with two fields, named values stored inside it: val, the value it holds, and next, the node that comes after it. The last node's next is None, Python's value for "nothing here". Here is the whole class:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val # the value this node holds
self.next = next # the node after this one, or None
Writing ListNode(3) makes a new node and runs __init__ on it, the constructor from the prefix sums lesson: self is the new node, val is 3, and next stays None because we gave no second value. ListNode(3, other) would make a node whose next is other. Every code cell in this lab already has this class, with exactly these two fields, so you never type it. LeetCode shows the same class in a comment above its linked list problems.
We call next a pointer, or a link: it does not hold a copy of the next value, it leads to the next node itself. A linked list is a chain of nodes that you hold by its first node, the head. From the head you can reach every node by following pointers. An empty list has no nodes, so its head is None.
The trace below builds a three-node list by hand. In the state panel, under "Linked nodes", each node is a box with its value and an arrow to the next node, and the chain ends in None. A name that points at a node shows as a tag above that box. Before you step through, guess what the last line prints.
head = ListNode(3)head.next = ListNode(8)head.next.next = ListNode(5)print(head.val, head.next.val, head.next.next.val)
(nothing printed yet)head.next.next reads left to right: start at head, follow one pointer to the 8, follow another to the 5. And = never copies a node. It makes a name point at a node that already exists, so two names can lead to the same box. Try that now. build_list([3, 8, 5]) is a lab helper that builds the chain 3 → 8 → 5 and returns its head, and list_values(head) walks a chain and returns its values as a Python list.
Type exactly what this prints. build_list([3, 8, 5]) builds the chain 3 → 8 → 5 and returns its head, and list_values(head) returns the values of a chain as a Python list.
head = build_list([3, 8, 5])
cur = head.next
cur.val = 7
print(list_values(head))
print(cur.next.val)
A linked list has no indexes. To reach the 5 you must start at the 3 and follow two pointers. In general, the node at position k (counting from 0, like a list index) takes k steps from the head. As module 3 showed, a Python list keeps its items side by side in memory, so nums[k] is one step, but inserting at the front shifts every item one slot right.
In exchange, the front of a linked list is cheap. head = ListNode(1, head) makes a node whose next is the old head (the right side runs first, so head there is still the old head), then moves the name head onto the new node. No other node changes. Before you step through, guess what the list holds at the end.
head = build_list([3, 8, 5])head = ListNode(1, head)print(list_values(head))
(nothing printed yet)A linked list (you hold only its head) and a Python list hold the same n values. Which operation takes a fixed number of steps on the linked list, however long it is, but grows with n on the Python list?
Choose one answer, then check.
Walking the chain
How do you visit every node when all you hold is the head?
Use a second name, cur (short for current), and move it one node at a time. cur = cur.next points cur at the node after the one it points at now. When cur becomes None, it has walked off the end, so the loop runs while cur is not None. is asks whether two things are the very same object, and Python has only one None, so cur is not None is true exactly while cur is on a real node. The trace adds up the values of 3 → 8 → 5. Before you step through, guess: what does total hold the first time cur is None?
def list_sum(head):total = 0cur = headwhile cur is not None:total += cur.valcur = cur.nextreturn total
(nothing printed yet)cur = cur.next changed no node. It moved a tag. This difference matters on every line of the rest of this module:
This is the pagination loop from the start of the lesson: use what the current page holds, follow its cursor, and stop when there is none.
The loop tests cur, not cur.next. Here is what the other test does:
This version tests cur.next instead of cur:
def list_sum(head):
total = 0
cur = head
while cur.next is not None:
total += cur.val
cur = cur.next
return total
What does list_sum(build_list([3, 8, 5])) return?
Choose one answer, then check.
The running maximum from module 1 works on a chain too. There, best started at the first item and for x in nums handed out the rest. Here the first item is head.val, and a while loop with cur = cur.next does the handing out.
Write largest_value(head), which returns the largest value in a linked list that has at least one node. Walk the chain with cur instead of calling max(list_values(head)): the point is the walk. Then press Watch it run to see cur move along the chain.
raise NotImplementedError, then press Run tests. Each check says what it expects.Reversing a list in place
How do you turn 3 → 8 → 5 into 5 → 8 → 3 without making new nodes?
Reversing means pointing every arrow the other way. No node changes its value. The 5, which points at None, must point at the 8, and it becomes the new head. The 8, which points at the 5, must point at the 3. The 3, the old head, must point at None, because it becomes the last node. Doing it in place means changing the pointers of the nodes we already have: no new nodes, no copy.
The first move that comes to mind, at the 3, is to set its next to None right away. Predict what that does to the rest of the list.
This tries to start a reversal by pointing the first node back at prev straight away, before saving anything. Type exactly what it prints.
head = build_list([3, 8, 5])
prev = None
cur = head
cur.next = prev
cur = cur.next
print(cur)
print(list_values(head))
A node's next is the only way to reach the nodes after it. Cut it, and they are gone. So save the rest before you cut. The walk keeps three names:
prev, the head of the part already reversed (at firstNone: nothing is reversed yet);cur, the node we are on;nxt, the rest of the list, saved beforecur.nextchanges.
Each pass makes four moves, in this order: nxt = cur.next saves the rest; cur.next = prev points the current node back; prev = cur makes it the head of the reversed part; cur = nxt steps into the rest. After every flip but the last, the drawing shows two chains: the reversed part and the rest. Before you step through, guess which node head points at when the loop ends.
def reverse_list(head):prev = Nonecur = headwhile cur is not None:nxt = cur.nextcur.next = prevprev = curcur = nxtreturn prev
(nothing printed yet)To recap: save, flip, move prev, move cur, in that order, once per node. Each pass moves one node from the front of the rest to the front of the reversed part, so when the rest is empty, prev heads the whole list reversed. Now do it on paper, the way you would at a whiteboard.
Reverse 1 → 2 → 3 → 4 on paper with the four moves: nxt = cur.next, cur.next = prev, prev = cur, cur = nxt. After each pass, draw two chains: the one prev heads and the one cur heads. Then answer: right after pass 3, what is prev.next.val?
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now write it from a blank editor. Say the promise to yourself before you type.
The empty list and the single node need no extra code. With head = None the loop never runs and prev is still None. With one node, one pass points it at None and returns it.
The problem's follow-ups also ask why a loop beats recursion here. A recursive reversal is a function that calls itself on the rest of the list. It keeps one call waiting per node, and module 2 showed that every waiting call holds its own box of names: O(n) extra space. Plain Python also stops at about 1,000 nested calls by default, so a long list can fail. The loop needs three names, however long the list.
A placeholder in front: the dummy head
How do you build a new list one node at a time, adding each new node at the end?
Keep a name, tail, on the last node, so you never walk from the head to find the end. Attaching takes two moves: tail.next = node links the new node after the last one, and tail = tail.next moves tail onto it. The first node breaks this. Before it, there is no last node: if tail starts as None, the first tail.next = node raises an AttributeError. Without a trick, the first node needs its own branch:
def build_without_dummy(values):
head = None
tail = None
for v in values:
node = ListNode(v)
if head is None: # the first node: there is nothing to attach it to
head = node
else:
tail.next = node
tail = node
return head
A dummy head removes the special case. A dummy head (also called a dummy node) is a placeholder node made first, dummy = ListNode(), that sits in front of the answer. Start tail on it. Now there is always a last node, so every attach, the first one included, is the same two moves. When the walk ends, the answer starts at dummy.next, the node after the placeholder. The trace builds 4 → 9 → 2 from a Python list. Before you step through, guess which node the function returns.
def build(values):dummy = ListNode()tail = dummyfor v in values:tail.next = ListNode(v)tail = tail.nextreturn dummy.next
(nothing printed yet)The lab's own build_list helper is this function. Now put a variation together: it keeps only some of the values.
Put the lines in order to build keep_above(values, limit). It takes a Python list and returns the head of a new linked list that holds, in their original order, only the values bigger than limit, or None if there are none. Indentation is part of each line. Two of the lines do not belong.
Add lines from the list below, in order.
tail = ListNode(v)return dummy.nexttail = dummyreturn dummyfor v in values:def keep_above(values, limit):tail = tail.nextif v > limit:tail.next = ListNode(v)dummy = ListNode()
Merging two sorted lists
How do you combine two sorted lists into one sorted list, using the nodes you already have?
Take 2 → 6 and 1 → 3 → 4. The smallest node not used yet is always at the front of one of the two lists, because each list is sorted. So compare the two fronts, attach the smaller one behind tail, and step that list forward.
When one list runs out, attach the rest of the other in one move. It is already sorted, and none of its nodes is smaller than anything attached so far. The dummy head makes the first attach the same as all the others.
Before you step through, guess which list runs out first, and which node the last line attaches.
def merge_two_lists(list1, list2):dummy = ListNode()tail = dummywhile list1 is not None and list2 is not None:if list1.val <= list2.val:tail.next = list1list1 = list1.nextelse:tail.next = list2list2 = list2.nexttail = tail.nexttail.next = list1 if list1 is not None else list2return dummy.next
(nothing printed yet)The merge loop runs while both lists still have a node, and each pass attaches one node. When list1 is 1 → 2 and list2 is 3 → 4 → 5, how many passes does the loop make? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now write the merge yourself. The problem's examples include two empty lists and a value that appears in both lists.
Ties and empty lists need no extra code either. When the fronts are equal, <= takes the node from list1, and the problem allows either order. When one list is empty, the loop never runs and the last line attaches the other list whole. When both are empty, it attaches None, so dummy.next is None. The tests also check that the answer is made of the given nodes, which is why the merge only changes next pointers and makes no new node apart from the placeholder.
Two more problems in this module's practice bank use these moves. In Remove Linked List Elements (LeetCode 203), a dummy head in front of the real head, ListNode(0, head), lets you remove the first node like any other. Add Two Numbers (LeetCode 2) builds its answer behind a dummy head, one digit node at a time. The next lesson walks two names through one list, at two speeds or with a fixed gap between them. The last one builds an LRU cache from a dictionary and a doubly linked list, whose nodes point both forward and back.
Last, say it out loud. The words you write here are the words you will use in the room.
Explain, as you would to an interviewer before typing, how you would reverse a linked list in place. Cover the walk, the notebook, the promise and the cost, and say what your code does on an empty list.
Saved in this browser as you type.