Linked lists
Work with nodes and pointers: reverse a list and find its middle with the slow and fast pointer trick.
24 min
A linked list is a chain of nodes. Each node holds a value and a reference (next) to the following node; the last one points to None. You hold only the head, the first node.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next1 → 2 → 3 is ListNode(1, ListNode(2, ListNode(3))).
| Operation | Array (Python list) | Linked list |
|---|---|---|
Read item i | O(1) | O(i): walk from the head |
| Insert or delete after a known node | O(n) shift | O(1): rewire pointers |
| Insert at the front | O(n) | O(1) |
Interviews love linked lists because they test careful thinking about pointers. Pictures help: draw boxes and arrows.
node = head
while node:
print(node.val)
node = node.nextReverse by flipping each arrow as you walk. Keep three things: where you came from (prev), where you are (cur), and where you were going (nxt), which you must save before you overwrite cur.next:
prev, cur = None, head
while cur:
nxt = cur.next # 1. remember the rest
cur.next = prev # 2. flip the arrow
prev = cur # 3. step forward
cur = nxt
return prev # the new headO(n) time, O(1) space.
Move slow one step and fast two steps at a time. When fast reaches the end, slow is at the middle. The same trick detects a cycle: if there is a loop, fast eventually laps slow and they meet.
An empty list (head is None), a single node, two nodes, and, for deletion, removing the head. A dummy node placed before the head removes most of the special cases.
Before reversing: 1, 2, 3. After: the arrows flip and 3 becomes the head.
Write reverse_list(head) that reverses the linked list and returns the new head. Use O(1) extra space. The helpers from_list and to_list are given for building and reading lists; leave them as they are.
to_list(reverse_list(from_list([1, 2, 3]))) is [3, 2, 1].
Your code must satisfy
- to_list(reverse_list(from_list([1, 2, 3])))→[3,2,1]three nodes
- to_list(reverse_list(from_list([])))→[]empty
- to_list(reverse_list(from_list([7])))→[7]one node
- to_list(reverse_list(from_list([1, 2])))→[2,1]two nodes
- to_list(reverse_list(from_list([5, 4, 3, 2, 1])))→[1,2,3,4,5]five nodes
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def from_list(values):
head = None
for v in reversed(values):
head = ListNode(v, head)
return head
def to_list(head):
out = []
while head:
out.append(head.val)
head = head.next
return out
def reverse_list(head):
passWrite middle_value(head) returning the value in the middle node of a non-empty list. For an even number of nodes, return the second of the two middle values (so [1, 2, 3, 4] gives 3). Make one pass using a slow and a fast pointer. For an empty list return -1.
Your code must satisfy
- middle_value(from_list([1, 2, 3]))→2odd
- middle_value(from_list([1, 2, 3, 4]))→3even
- middle_value(from_list([9]))→9single
- middle_value(from_list([5, 6]))→6two
- middle_value(from_list([]))→-1empty
- middle_value(from_list([10, 20, 30, 40, 50]))→30five
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def from_list(values):
head = None
for v in reversed(values):
head = ListNode(v, head)
return head
def middle_value(head):
pass“Reversing a list just means changing the order of the values.”
With a Python list, reversing is exactly that.
What is actually true
In a linked list you change the arrows, not the values. If you overwrite cur.next before saving it, you lose the rest of the list.
How to catch yourself
Say it as a rule: "save next, flip, step."
- A linked list is nodes with
valandnext; you hold the head. - Reaching item
icosts O(i), but inserting or deleting after a known node is O(1). - Reverse with
prev,curand a savednext; slow and fast pointers find the middle or a cycle. - Check empty, one-node and two-node lists, and use a dummy node to simplify deletion.
Pointer checks.
What does the last node's next hold?
- AThe head
- B`None`
- C0
- DItself
Why save nxt = cur.next before cur.next = prev?
- APython requires it
- BOtherwise you lose the rest of the list
- CIt is faster
- DTo avoid recursion
When fast reaches the end of a 5-node list, which node is slow on?
- AThe 2nd
- BThe 3rd
- CThe 4th
- DThe 1st
Which is O(1) in a linked list, given the node?
- AReading the 100th item
- BInserting a new node right after it
- CSorting
- DFinding the length
The first node of a linked list is called the .
Capitalisation, spacing and punctuation are ignored when grading.
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Coding Interview Prep: Data Structures and Algorithms is planned around your week. Free.