Reverse Linked List
How to Reverse a Linked List?
Reversing a linked list is a fundamental problem in coding interviews. It’s an essential skill because it helps you understand how to work with pointers, traverse a list, and is often used as part of more complex problems.
Understanding the Problem
Let’s take a simple linked list: 1 -> 2 -> 3 -> 4. After reversing it, the result should be 4 -> 3 -> 2 -> 1.
To make it even simpler, imagine reversing just 1 -> 2.
Get Alan Martins’s stories in your inbox
Join Medium for free to get updates from this writer.
Currently, Node 1 points to Node 2, and Node 2points to null.
After reversing, Node 1 should point to null, and Node 2 should point to Node 1.
To do this, we need to traverse the list and update the pointers for each node. At the end, we return the last node, which becomes the new head of the reversed list.
How the Algorithm Works
The problem can be broken down into simple steps:
- Set the
previousandcurrentpointers.previousstarts asnull(since nothing comes before the head).currentstarts as the first node (Node 1). - Start at the first node (
Node 1).Node 1is thecurrent.previousisnullbecause nothing is pointing toNode 1.
- Reverse the pointer for the current node.
MakeNode 1point toprevious(which isnull).
— Move the pointers forward:
—previousbecomesNode 1.
—currentbecomesNode 2.
- Repeat the process for the following nodes.
- Make
Node 2point toNode 1 - Make
previoustoNode 2andcurrenttoNode 3
- Continue until
currentbecomesnull.
This means we have reached the end of the list.
- The
previousis now the new head of the reversed list.
- Returnprevious
Step-by-Step Example
Step 1: Initialize pointers
- Create two pointers:
previous = None(no node before the head)current = head(start from the head of the list)
previous = None
current = headStep 2: Traverse and reverse pointers
- While
currentis notNone:
Save the next node in a temporary variable.
Reverse the pointer (current.next = previous).
Moveprevioustocurrent.
Movecurrentto the next node (saved in the temp variable).
while current:
next_node = current.next
current.next = previous
previous = current
current = next_nodeStep 3: Return the new head
- After the loop ends,
previouswill be the new head of the reversed list.
return previousThis solution has O(n) time complexity because it traverses the list once, and O(1) space complexity because it uses only a few pointers.
Full solution
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head):
previous = None
current = head
while current:
next_node = current.next
current.next = previous
previous = current
current = next_node
return previousCan You Solve It with Recursion?
This problem can also be solved using recursion instead of a loop. :)






