Skip to content
CodeItRaw
Linked Lists

Lesson 4/4

Reversing a linked list is turning each node's next link back to the node before it. The only hard part is the order: the moment you turn a link you lose the way to the rest of the chain. So before turning it you set the next node aside.

previous = None
node = head
while node is not None:
following = node.next
node.next = previous
previous = node
node = following
return previous
Four lines, always in this order: save the following one, turn the link, move previous on, move node on. When the loop ends node is empty; the head of the reversed list is in previous.

This is a building block of larger solutions. To tell whether a chain is a palindrome without copying it into a list: find the middle with the fast and slow pointers, reverse the second half, then walk the two halves together from their starts, comparing.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Reverse the List

    Code reading · Bug Hunt

  2. 02

    Chain Palindrome

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list