Reverse a section, every k nodes or half a list in place, and use it to check palindromes and reorder a list.
Your chat app keeps each thread as a chain of nodes, as in the first lesson. Your team lead brings four requests that sound different:
All four have the same shape. The nodes stay where they are in memory, and some of the arrows between them turn around. That is reversing in place. It needs one walk and a few cursors, however long the thread is.
Picture a line of friends. Each friend holds the hand of the friend next in line, and the last friend holds nobody. To turn the line around, you start at the front.
The first friend lets go and holds nobody. The second friend lets go of the third and takes the hand of the first, and so on down the line.
Before any friend lets go, someone must remember who stands next in line. Otherwise the rest of the line wanders off. Nobody walks to a new place, and only the holds change. In a chain, the friends are nodes, the holds are next pointers, and remembering who stands next is saving curr.next.
A chain is a line of friends holding hands: to turn it, each friend remembers who is next, then takes the hand behind.
A reversal creates no node and moves no node. Each node keeps its address, and only the stored next addresses change. The old head ends up holding null, and the old last node becomes the head. Step through the picture and notice that every address stays where it is.
Step by step: A chain in memory: reversing moves no node. The animated player loads in your browser.
Three words come up in every operation below:
left to position right, counted from 1 at the head.k consecutive nodes. A chain is cut into groups from the head.Predict what happens
Q A chain 1 → 2 → 3 is reversed in place. Afterwards, which node's next pointer holds null?
Answer: B
Reversal turns every arrow around. The old head had nothing before it, so it now points at null, and node 3 becomes the head.
Reversing a whole chain uses three cursors: prev, curr and a saved next. In each round you save curr.next, point curr.next back at prev, then move prev to curr and curr to the saved node.
The loop keeps one fact true. Before each round, prev is the head of a reversed chain that holds every node before curr, and curr is the first node not yet turned. When curr is null, prev heads the whole reversed chain.
Predict each arrow before the player shows it.
Step by step: Reverse a four-node list. The animated player loads in your browser.
Exercise · Put it in order: The reversal loop. Arrange the lines into a function that reverses a whole chain in place and returns the new head.
def reverse_list(head):
prev = None
curr = head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
curr = curr.nextTo reverse only the positions from left to right, run the same loop on those nodes only, then fix the two ends. Take 10 → 20 → 30 → 40 → 50 with left = 2 and right = 4.
before to the node right ahead of position left. That is 10, one hop from the head.start, the first node of the section. It is 20, and it will end up at the end of the section.right - left + 1 rounds, here 3. prev starts at null and curr at 20.before at prev, so 10 leads to 40. Point start at curr, so 20 leads to 50.Here are the three rounds of step 3. Each row saves next, turns one arrow, then moves prev and curr on.
| Round | prev | curr | next (saved first) | Arrow turned | prev, curr after the round |
|---|---|---|---|---|---|
| 1 | null | 20 | 30 | 20 now points at null | 20, 30 |
| 2 | 20 | 30 | 40 | 30 now points at 20 | 30, 40 |
| 3 | 30 | 40 | 50 | 40 now points at 30 | 40, 50 |
After round 3, prev is on 40, the new first node of the section, and curr is on 50, the node after it. The loop alone leaves two loose ends: 10 still points at 20, and 20 points at null. If you forget either link in step 4, nodes are lost.
Exercise · Predict the output: What does the chain read?. A chain 1 → 2 → 3 → 4 → 5 → 6 has positions 2 to 5 reversed. The code turns the arrows and sets before.next, then prints the chain from the head. What does it print?
class Node:
def __init__(self, val, nxt=None):
self.val, self.next = val, nxt
head = None
for v in [6, 5, 4, 3, 2, 1]:
head = Node(v, head)
before = head
prev, curr = None, before.next
for _ in range(4):
nxt = curr.next
curr.next = prev
prev, curr = curr, nxt
before.next = prev
node = head
while node:
print(node.val, end=" ")
node = node.nextStep 1 needs a node before the section. When left = 1, the section starts at the head and nothing comes before it. You could write a special case: reverse, then make prev the new head. The usual trick is a placeholder (often called a dummy node): one extra node, created before the work starts, whose next is the head.
dummy = ListNode(0, head) # its value is never read
before = dummy # walk left - 1 hops from here
...
return dummy.next # the real head, even if it changedNow every position, including position 1, has a node before it. Walking left - 1 hops from the placeholder lands on the node before the section: the placeholder itself when left = 1. Return dummy.next, never the old head: if the head moved, head now points at a node inside the list. The placeholder costs one node, whatever the length, and the caller never sees it.
The same trick serves every problem below where the first node can change: groups of k and pair swaps.
Exercise · Break it: Find the input this section reversal gets wrong. This function reverses positions left to right of a chain, but it has no placeholder node. Find an input where it gives the wrong answer.
def reverse_between(head, left, right):
before = head
for _ in range(left - 2):
before = before.next
start = before.next
prev, curr = None, start
for _ in range(right - left + 1):
nxt = curr.next
curr.next = prev
prev, curr = curr, nxt
before.next = prev
start.next = curr
return headReverse a stretch: turn its arrows with prev, curr and next, then link both ends: the node before, and the old first node.
The loop inside the section is the whole-chain loop on three nodes. Watch it on its own.
Step by step: A section on its own: 20, 30, 40. The animated player loads in your browser.
Predict what happens
Q In the section example, the loop has run on 20, 30 and 40. Which two pointers must you still set?
Answer: A
After three rounds, prev is on 40, the new first node of the section, and curr is on 50. The node before the section must lead to prev, and the old first node must lead to curr.
To reverse every k nodes, repeat the section reversal along the chain. Three rules keep it correct. Take 1 → 2 → 3 → 4 → 5 → 6 → 7 with k = 3.
k nodes remain. Walk k nodes ahead of the node before the group. If the chain ends first, the last group is short. Stop, and leave it as it is.prev at the node after the group. Then the old first node already points into the next group.Here is group 1 pointer by pointer. group_prev starts on the placeholder. Walking 3 nodes from it lands on 3, so the group is full, and the node after it is 4.
| Round | prev | curr | Arrow turned |
|---|---|---|---|
| start | 4, the node after the group | 1 | |
| 1 | 4 | 1 | 1 now points at 4 |
| 2 | 1 | 2 | 2 now points at 1 |
| 3 | 2 | 3 | 3 now points at 2 |
curr has reached 4, so the group is done. The placeholder now points at prev, which is 3, and group_prev moves to 1, the old first node, which already leads to 4. Group 2 repeats the same moves from 1. For group 3, the walk from 4 finds only 7 and then null, so it stops.
The result is 3 → 2 → 1 → 6 → 5 → 4 → 7: two full groups reversed, and the short group of one left in place.
With k = 2 every group is a pair, and the reversal shrinks to three pointer changes. For a pair first, second after before: first.next = second.next, then second.next = first, then before.next = second, and before moves to first. The order matters, because second.next is the only way to reach the rest of the chain until first holds it.
Reverse every k nodes: check that k nodes remain, reverse with prev starting after the group, link the groups together, and leave a short last group alone.
Predict what happens
Q You reverse every 3 nodes of 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8. What does the chain read afterwards?
Answer: B
The groups are 1 2 3, then 4 5 6, and then 7 8, which has only 2 nodes. A short last group is not reversed, so 7 and 8 keep their order.
A chain cannot be read backwards. But if you reverse its second half, the old last node becomes the first node of that half. Then two walkers can read both halves from their first nodes, towards the middle.
Find the second half with slow and fast. Both start at the head, slow moves one node, and fast moves two, while fast and fast.next are not null. When the loop stops, slow is on the first node of the second half:
Watch slow stop on six nodes. The second half starts where it stops.
Step by step: The middle of six nodes. The animated player loads in your browser.
Exercise · Find the bug: The half that starts one node early. This function should return the first node of the second half: the middle node of an odd chain, the second middle of an even one. On some chains it returns one node too early. Which line is wrong?
def second_half_start(head):
slow = fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slowTwo uses follow:
left from the head and right from the reversed half's head, comparing node by node. With an odd length the middle meets itself. Then reverse the half again.fast.next and fast.next.next are not null. Slow then stops on node 3 for both 5 and 6 nodes. Cut after slow, reverse the second half, and weave: after each node of the first half, put one node of the reversed second half.After you reverse from slow, the first half still leads into the old first node of the second half. That node is now the last of the reversed half. So a walk from the head reads the first half and that one node, and nothing else.
Turning the half back is one more reversal, because reversing twice gives the original chain.
Step by step: Reverse twice and the chain is back. The animated player loads in your browser.
Check a palindrome: find the second half with slow and fast, reverse it, compare the two halves from their first nodes, and turn the half back.
Predict what happens
Q In 3 → 8 → 5 → 8 → 3, you reverse from slow, the middle node 5, and do nothing else. What does a walk from the head read?
Answer: B
The node 8 before the middle still points at 5, and 5 now points at null. The reversed half, 3, 8, 5, can only be reached from its new head, the last 3.
Every move below is one walk, or a few, and a few pointers of extra memory. Copying into an array first costs memory for every node.
| Operation | In place on the chain | Copy to an array, reverse, write back |
|---|---|---|
| Reverse the whole list, from the head | O(n) time, O(1) memory | O(n) time, O(n) memory |
| Reverse the first k nodes, at the front | O(k) time, O(1) memory | O(k) time, O(k) memory |
| Reach the node before a section, by index | O(left): one hop per node | O(1) once the array exists, after an O(n) copy |
| Find where a section starts, by searching for a value | O(n) | O(n) |
| Reverse the second half, from the middle to the end | O(n) time, O(1) memory | O(n) time, O(n) memory |
| Find the middle with slow and fast | O(n) time, O(1) memory | O(n) to copy, then O(1) |
| Reverse every k nodes | O(n) time, O(1) memory | O(n) time, O(n) memory |
The wins are in the memory column, and in never moving a node. The cost you pay is the walk to reach a place.
The O(1) memory holds for the loops in this lesson. A recursive reversal reverses the rest of the chain, then hooks the current node on at the end. It is shorter to write, but it keeps one call per node on the call stack: O(n) memory. On 10^5 nodes it passes Python's default limit of 1,000 calls and raises an error, so use the loop.
Now drive the chain yourself. Pick an operation, watch it step by step, and read the hop counter. Reversal and the middle are the two operations the sandbox knows, and they are the building blocks of this lesson.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the moves yourself. The lab gives you a Node class and a ReversibleList class that keeps head and count. You write four methods: push_back, reverse_first, reverse_second_half and size. The fifth, to_list, is already written, so the tests can look inside your list.
The two reversal methods are the two special cases of a section.
reverse_first(count) starts at the head, so the head changes. reverse_second_half() runs to the end, so no node follows it.
Together they show both reconnecting steps of the section reversal.
Three rules keep the list correct after every method:
head is the first node, or null when the list is empty.count goes up by one on each push_back, and no reversal changes it.head, in the new order.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Reverse in place when the data already lives in a chain and you cannot afford a copy. A palindrome check or a reorder of a long chain needs only a few cursors. Reversing a stretch or a group relinks a few nodes, while an array would shift or copy every item after it.
In an interview, in-place reversal is the standard way to show that you can work with pointers and keep the memory fixed.
Do not reverse a chain in place while another part of the program is reading it. Halfway through, the chain is cut in two, and the reader sees a short list, or turns back and reads nodes it has already read. In that case copy, or reverse a copy.
If the chain is short and you need random access, read it into an array. And if you need to walk in both directions often, use a doubly linked list, which keeps a prev pointer and never needs the reversal.
After the loop in a section reversal, the old first node still points at null. If you set before.next = prev but forget start.next = curr, everything after the section is cut off. On 10 → 20 → 30 → 40 → 50 with left = 2 and right = 4, the chain reads 10, 40, 30, 20, and 50 is lost. Always set both links.
The classic mistake in a stretch reversal: set only the link from the node before, and the nodes after the stretch are lost.
If a group loop reverses whatever remains, the last group is turned even when it has fewer than k nodes. On 1 → 2 → 3 → 4 → 5 with k = 3, you get 3, 2, 1, 5, 4 instead of 3, 2, 1, 4, 5. Walk k nodes ahead first, and stop when the chain ends.
In a group reversal, prev = None at the start of each group makes the old first node point at null. The next group is cut off. On 1 → 2 → 3 → 4 → 5 → 6 with k = 3, the chain reads 3, 2, 1 and the second group is lost. Start prev at the node after the group, so the old first node already points into it.
To swap a pair, write first.next = second.next before second.next = first. If you write second.next = first first, then first.next = second.next points first at itself, because second.next has already been overwritten. On 1 → 2 → 3 → 4 the code never finishes: node 1 points at itself, and the loop keeps finding a "pair" there. Save what you are about to overwrite, then change the pointer.
curr.next, point curr back at prev, then move on.right - left + 1 rounds, and two links at the end.prev starting after the group, and a link from group to group.Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · The idea
Q1/2 What does reversing a linked list in place change?
Answer: C
In place means the nodes you already have are reused. Each next pointer turns around, and nothing is created or moved.
Q2/2 At the start of a round in the reversal loop, what is true about prev?
Answer: B
prev starts as null, the empty reversed chain. Each round adds curr to the front of that chain, so prev always heads the nodes already turned.
Checkpoint · Sections
Q1/3 You reverse positions 3 to 7 of a chain with the three-cursor loop. How many rounds does the loop run?
Answer: B
Positions 3, 4, 5, 6 and 7 are five nodes. Both ends count, so the number of rounds is right - left + 1.
Q2/3 You reverse positions 2 to 4 of 10 → 20 → 30 → 40 → 50 and forget start.next = curr. What does the chain read from the head?
Answer: C
The old first node, 20, still points at null after the loop, so nothing leads to 50. The chain reads 10, 40, 30, 20, and 50 is lost.
Q3/3 Why does a section reversal put a placeholder node before the head?
Answer: A
Every section needs a node before it, to be linked to the new first node. The placeholder is that node when the section starts at the head.
Checkpoint · Groups
Q1/2 You reverse every 4 nodes of 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10. What does the chain read?
Answer: C
The groups are 1 to 4, 5 to 8, and then 9 and 10, which is a short group of 2. A short last group is not reversed.
Q2/2 In a group reversal, why does prev start at the node after the group instead of at null?
Answer: B
The first round turns the old first node's arrow back at prev. If prev is the node after the group, that arrow points at the next group, and the groups stay linked.
Checkpoint · Halves
Q1/3 slow moves one node and fast moves two, both from the head of 2 → 6 → 6 → 2. When fast runs off the end, where is slow?
Answer: B
Round 1: slow 6, fast 6. Round 2: slow on the second 6, and fast moves past the end. With an even length slow stops on the first node of the second half.
Q2/3 A palindrome check reverses the second half, compares, and returns without turning the half back. Why does a second call on the same chain go wrong?
Answer: B
After the reversal, the node before the middle still points at the middle, and the middle points at null. A walk from the head sees only the first half and the middle, so the second call compares the wrong nodes.
Q3/3 After the cut, a reorder of oldest, newest, second oldest, second newest and so on needs which two steps?
Answer: C
The new order reads the first half forwards and the second half backwards. Reversing the second half makes it readable forwards, and the weave takes one node from each half in turn.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.