Crushing Tech Interviews with the Linked List Reversal Pattern
Ah, a good old linked list problem. Some people love them, some people help them.
Hopefully with this pattern, you'll love questions which ask you to reverse the links between a set of nodes of a linked list. It may sounds like a niche pattern but it's one that comes up time and time again.
So how do we do it?
We reverse a linked list one node at a time. We have three variables: current
, previous
and temp
. Juggling these pointers is what allows you to solve this question.
For each step, we reverse the current
node by pointing it's next
value to the previous
pointer. Simple right? Not so much... we need to be careful when we do this because if we lose a reference to a node, that node is lost! Thats where the temp
variable comes into play; to ensure that we're keeping track of everything.
It sounds a bit confusing but let me show you via some diagrams:
Note: the null
at the beginning isn't the head. I've put it there to make the diagram more understandable.
- We set the
current
pointer to thehead
value, thetemp
andprevious
values toNone
/null
(depending on your programming language). - We set the
temp
value tocurrent.next
. Think about what happens if we don't do this step. - We set the
current.next
value toprevious
; essentially turning the link from → to ←. - We move the
previous
pointer tocurrent
and then we move thecurrent
pointer up one element.current = current.next
. If we move thecurrent
element first, we will lose our reference to that node!
class LinkedListNode:
def __init__(self, value, next_node):
self.value = value
self.next_node = next_node
def reverse_linked_list(head: LinkedListNode):
previous_node, temp_node, current_node = None, None, head
while current_node is not None:
temp_node = current_node.next_node
current_node.next_node = previous_node
previous_node = current_node
current_node = temp_node
return previous_node
Work through each step one by one and you'll be able to crack it!
Here's some more questions that you can have a crack at:
https://leetcode.com/problems/palindrome-linked-list/ (Easy)
https://leetcode.com/problems/reverse-linked-list-ii/ (Medium)
If you enjoyed this article, please go support the people over at https://www.educative.io/courses/grokking-the-coding-interview I've based this blog post on their content.