How To Reverse a LinkedList
Imagine we have the following data structure for a node in a Linked List.
We start out with a linked list like this
The variable head
points at 0.
There are a few constraints when solving this problem
- Your solution should absolutely be
O(n)
- Use as few variables as possible - management of the pointers is what makes this problem challenging
Walking through each iteration helped me.
We set A.next
to prev
, then iterate forward. The variable B
really just exists so we can iterate forward once we point A.next
elsewhere.
Note that prev
now points at the new head
.
Here’s the final solution.
You can get rid of the if b is not None else None
section if you rearrange the order in which you set everything (you set b = a.next
before you do a.next = prev
, but honestly I find that harder to reason about.
This solution has O(n)
time complexity and O(1)
space complexity.
Wow! You read the whole thing. People who make it this far sometimes
want to receive emails when I post something new.
I also have an RSS feed.