Sub topic 6
Reversal, middle node, and cycle detection
This chapter covers three pointer techniques on singly linked lists that GATE CS tests often: reversing a list, finding the middle node, and detecting a cycle. It assumes you know how a singly linked list stores nodes with a next reference, how traversal works, and basic Big-O notation. Each technique runs in O(n) time and O(1) extra space.
Why these three techniques matter
A singly linked list only lets you move forward. You cannot step back, and you cannot jump to the middle by index. These techniques work around that limit using a small number of extra references. They never allocate a second list or an auxiliary array.
The techniques also combine. Palindrome checks on a list, for example, find the middle, reverse the second half, and compare the two halves.
Reversing a singly linked list
Reversal redirects each node's next pointer to the node before it. You need three references:
previs the already reversed part. It starts asNone.headis the current node being processed.nxtis a saved copy ofhead.next, taken before the link is overwritten.
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def reverse(head):
prev = None
while head is not None:
nxt = head.next
head.next = prev
prev = head
head = nxt
return prevThe order of the four statements inside the loop matters. If you overwrite head.next before saving it, you lose the rest of the list.
Tracing the loop
Take the list 1 → 2 → 3. The table shows the state at the end of each iteration.
| Iteration | `nxt` | `head.next` after update | `prev` | `head` |
|---|---|---|---|---|
| Start | n/a | n/a | None | 1 |
| 1 | 2 | None | 1 | 2 |
| 2 | 3 | 1 | 2 | 3 |
| 3 | None | 2 | 3 | None |
The loop ends when head is None. At that point prev points to node 3, which is the new head of 3 → 2 → 1.
Cost and edge cases
- Time: each node is visited once, so O(n).
- Extra space: three references, so O(1).
- An empty list returns
None. - A one-node list returns that node unchanged, with
nextstillNone.
A recursive version also works, but it uses O(n) stack space for the call frames. GATE questions often ask about this difference.
Finding the middle node
You could count the nodes, then walk to position n/2. That takes two passes. The slow and fast pointer technique finds the middle in one pass.
Both pointers start at the head. In each step, slow moves one node and fast moves two. When fast reaches the end, slow is at the middle.
def middle(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
return slowWhich middle for even lengths
For an odd length, there is one middle node. For an even length, there are two candidates. This loop condition returns the second one.
| List | Result of `middle` |
|---|---|
| 1 → 2 → 3 | 2 |
| 1 → 2 → 3 → 4 | 3 |
| 1 → 2 → 3 → 4 → 5 | 3 |
| 1 → 2 → 3 → 4 → 5 → 6 | 4 |
To get the first middle in an even list, change the loop condition to fast.next is not None and fast.next.next is not None. Read exam questions carefully to see which middle they mean.
The fast.next is not None check must come after fast is not None. Python stops evaluating at the first false operand, so this order prevents an attribute error on None.
Cost
fast makes about n/2 steps and slow makes about n/2 steps. The time is O(n), and the extra space is O(1). This is still one traversal, so it is about twice as fast as the count-then-walk approach.
Detecting a cycle
A list has a cycle if some node's next points back to an earlier node. Traversal then never reaches None. A plain loop over such a list runs forever.
Floyd's algorithm, also called the tortoise and hare method, reuses the two-speed idea. If there is no cycle, fast reaches None. If there is a cycle, both pointers enter it, and fast gains one position on slow per step. Inside a loop of finite length, fast must eventually land on the same node as slow.
def has_cycle(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return FalseThe test uses is, which compares node identity. Comparing data values is wrong, because two different nodes can hold the same value.
Why the pointers must meet
Once both pointers are in the cycle, the distance between them, measured along the cycle, shrinks by 1 on every step. The fast pointer moves 2 and the slow pointer moves 1. The distance therefore goes down through every value until it reaches 0. It cannot skip over 0, so they meet. This is why a step of 2 works. A speed difference larger than 1 could in principle jump over the slow pointer in a different cycle length, although the pointers would still meet eventually.
The pointers meet within a number of steps proportional to the list length. The total time is O(n) and the extra space is O(1).
Alternative: a visited set
You can also store each visited node in a hash set and report a cycle when you see a node twice. This is simple and also O(n) time. It costs O(n) extra space, which is why Floyd's method is preferred when space matters.
| Method | Time | Extra space | Notes |
|---|---|---|---|
| Floyd (two pointers) | O(n) | O(1) | Modifies nothing |
| Visited set | O(n) | O(n) | Easy to extend, for example to count steps |
| Mark nodes as visited | O(n) | O(1) | Changes node data, so it is usually not allowed |
Finding where the cycle starts
After slow and fast meet, reset one pointer to the head. Then move both one step at a time. They meet again at the first node of the cycle.
def cycle_start(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow is fast:
ptr = head
while ptr is not slow:
ptr = ptr.next
slow = slow.next
return ptr
return NoneThe reason is arithmetic. Let the distance from the head to the cycle start be a, and let the cycle length be c. When the pointers meet, slow has taken some number of steps k, and fast has taken 2k. Their difference, k, is a multiple of c. So slow is k steps from the head, and walking another a steps from the meeting point brings it back to the cycle start, because k + a is also a multiple of c plus a... more precisely, k − a is the offset of the meeting point inside the cycle, and a further a steps lands on offset k, which is a multiple of c, the cycle start. A pointer from the head also takes a steps to reach the start. Both arrive together.
Putting the techniques together
A palindrome check on a list uses all of the ideas except cycle detection:
- Find the middle with slow and fast pointers.
- Reverse the second half starting at the middle.
- Walk the first half and the reversed half together, comparing
data.
This takes O(n) time and O(1) extra space. If you must restore the list afterward, reverse the second half again.
Common errors
- Forgetting to save
head.nextbefore overwriting it during reversal. - Returning
headinstead ofprevfromreverse, which gives the last node of the original list's wrong end. - Checking
fast.nextbefore checking thatfastis notNone. - Comparing node values instead of node identity when detecting a cycle.
- Assuming a particular middle for even lengths without reading the question.
Practice
Exercise
A singly linked list holds 10 → 20 → 30 → 40 → 50 → 60. The middle function from this chapter runs on it. Which node does it return, and how many times does slow move?
Show answer
It returns the node with data 40. The loop runs while fast and fast.next are not None. After step 1, slow is 20 and fast is 30. After step 2, slow is 30 and fast is 50. After step 3, slow is 40 and fast is None, so the loop stops. The slow pointer moved 3 times.
Exercise
In reverse, the statements nxt = head.next and head.next = prev are swapped, so head.next = prev runs first. What happens when you call it on 1 → 2 → 3?
Show answer
The link from node 1 to node 2 is overwritten with None before it is saved, so nxt becomes None. The loop ends after one iteration. The function returns node 1, and the list is now just node 1, because nodes 2 and 3 are no longer reachable from the head.
Exercise
Why does Floyd's cycle detection use O(1) extra space while the visited-set method uses O(n)?
Show answer
Floyd's method keeps only two references, slow and fast, whatever the list length. The visited-set method stores a reference to every node it has seen, so memory grows with the number of nodes.