iq.lab
Python starts when a code cell comes near or you run one
07 Linked lists

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.

About 1 hour 30 minutes, with the 2 problems worked in it
By the end you can
  • Draw a linked list as nodes and arrows, and say which node each name points at

  • Walk a linked list with cur = cur.next and stop safely at None

  • Reverse a linked list in place with prev, cur and nxt

  • Build a new list behind a dummy head with a tail name

  • Merge 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.

Step throughThree nodes, linked by hand
Step 1 of 5
Line 1 is about to run.
A new node holding 3. Its next is None for now.
head = ListNode(3)
head.next = ListNode(8)
head.next.next = ListNode(5)
print(head.val, head.next.val, head.next.next.val)
Names
no names yet
Output
(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.

PredictTwo names, one node

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.

Step throughA new node at the front
Step 1 of 4
Line 1 is about to run.
build_list links 3, 8 and 5 and returns the first node.
head = build_list([3, 8, 5])
head = ListNode(1, head)
print(list_values(head))
Names
no names yet
Output
(nothing printed yet)
Quick checkWhere a linked list wins

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?

Step throughWalking the chain to add up its values
Step 1 of 16
Line 1 is about to run.
def list_sum(head):
total = 0
cur = head
while cur is not None:
total += cur.val
cur = cur.next
return total
Names
no names yet
Output
(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:

Quick checkThe wrong stop test

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.

Code itThe largest value in a chain

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.

⌘+Enter runsPython starts when a code cell comes near or you run one
Write your code where the starter says 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.

PredictCutting before saving

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 first None: nothing is reversed yet);
  • cur, the node we are on;
  • nxt, the rest of the list, saved before cur.next changes.

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.

Step throughReversing three nodes in place
Step 1 of 22
Line 1 is about to run.
def reverse_list(head):
prev = None
cur = head
while cur is not None:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return prev
Names
no names yet
Output
(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.

On paperReverse four nodes on paper

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.

prev.next.val right after pass 3

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.

easyLinked lists target 15 min

Reverse a linked list

A linked list is a chain of nodes. Each node is a ListNode with two fields: val, its value, and next, the node after it (None after the last node). You get head, the first node of a list, or None if the list is empty.

Turn the list around, so its values read from last to first, and return its new first node. For an empty list, return None. The tests read the values of the list you return. The classic answer reuses the given nodes and changes only their next links.

Examples write a linked list as the list of its values: [3, 8, 5, 1] means 3 → 8 → 5 → 1, and [] is an empty list.

Example 1
Inputhead = [3, 8, 5, 1]Output[1, 5, 8, 3]

The last node, 1, is now the head, and the old head, 3, is now last.

Example 2
Inputhead = [6, 2]Output[2, 6]
Example 3
Inputhead = []Output[]

An empty list stays empty: return None.

Constraints
  • 0 ≤ number of nodes ≤ 5,000

  • -5,000 ≤ node value ≤ 5,000

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

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.

Step throughBuilding a list behind a placeholder node
Step 1 of 16
Line 1 is about to run.
def build(values):
dummy = ListNode()
tail = dummy
for v in values:
tail.next = ListNode(v)
tail = tail.next
return dummy.next
Names
no names yet
Output
(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 in orderKeep the big 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.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • tail = ListNode(v)
    • return dummy.next
    • tail = dummy
    • return dummy
    • for v in values:
    • def keep_above(values, limit):
    • tail = tail.next
    • if 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.

    Step throughMerging two sorted lists behind a dummy head
    Step 1 of 28
    Line 1 is about to run.
    def merge_two_lists(list1, list2):
    dummy = ListNode()
    tail = dummy
    while list1 is not None and list2 is not None:
    if list1.val <= list2.val:
    tail.next = list1
    list1 = list1.next
    else:
    tail.next = list2
    list2 = list2.next
    tail = tail.next
    tail.next = list1 if list1 is not None else list2
    return dummy.next
    Names
    no names yet
    Output
    (nothing printed yet)
    Work it outHow many passes?

    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.

    passes

    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.

    easyLinked lists target 15 min

    Merge two sorted lists

    You get list1 and list2, the first nodes of two linked lists. Each node is a ListNode with a value (node.val) and a link (node.next) to the node after it. Each list is sorted from smallest to largest (a value may repeat), and either one may be empty (None).

    Combine them into one list sorted from smallest to largest and return its first node, or None if both lists are empty. The answer must be made of the nodes you were given, relinked by changing their next links, not of new nodes. When the two lists hold equal values, either node may come first.

    Examples write a linked list as the list of its values: [1, 4, 6] means 1 → 4 → 6, and [] is an empty list.

    Example 1
    Inputlist1 = [1, 4, 6], list2 = [2, 4, 5]Output[1, 2, 4, 4, 5, 6]

    Take the smaller front node each time. The two 4s end up next to each other.

    Example 2
    Inputlist1 = [5], list2 = [1, 2, 3]Output[1, 2, 3, 5]

    Every node of list2 is smaller than 5, so list2 runs out first and the 5 goes on the end.

    Example 3
    Inputlist1 = [], list2 = []Output[]

    Two empty lists merge into an empty list: return None.

    Constraints
    • 0 ≤ number of nodes in each list ≤ 50

    • -100 ≤ node value ≤ 100

    • Each list is sorted from smallest to largest.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Say itSay it like you would 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.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Fast and slow pointers