DEV Community

Abinaya Dhanraj
Abinaya Dhanraj

Posted on

REVERSING THE LINKEDLIST

How I Understood Reversing a Linked List (LeetCode 206)
When I first saw this problem, reversing a linked list seemed tricky because we can’t access nodes by index like arrays.
After breaking it down step by step, it became clear that we can do it iteratively with just three pointers.

** Problem**
Given the head of a singly linked list, reverse the list and return its new head.
Example:
Python
Input: 1 -> 2 -> 3 -> 4 -> 5 -> None
Output: 5 -> 4 -> 3 -> 2 -> 1 -> None

What I Noticed
The key is to reverse the next pointers for each node.
To avoid losing the rest of the list, we need to store the next node before changing the pointer.

What Helped Me
Using three pointers made it very clear:
prev → initially None
curr → initially head
next_node → temporarily store curr.next
Step-by-step process for each node:
Save the next node (next_node = curr.next)
Reverse the current pointer (curr.next = prev)
Move forward (prev = curr, curr = next_node)
Repeat until curr becomes None. At the end, prev will point to the new head
.
Code (Python)
Python
from typing import Optional

class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next

class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
curr = head

    while curr:
        # 1. Save the rest of the list
        next_node = curr.next

        # 2. Reverse the pointer
        curr.next = prev

        # 3. Move pointers forward for the next iteration
        prev = curr
        curr = next_node

    # At the end, 'prev' will point to the new head
    return prev
Enter fullscreen mode Exit fullscreen mode

Example Usage
Python

Creating linked list: 1 -> 2 -> 3 -> None

head = ListNode(1, ListNode(2, ListNode(3)))
solution = Solution()
new_head = solution.reverseList(head)

Print reversed list

curr = new_head
while curr:
print(curr.val, end=" -> ")
curr = curr.next
print("None")
Output:
Plain text
3 -> 2 -> 1 -> None
⏱️ Complexity
Time: O(n) — iterate through the list once
Space: O(1) — only a few pointers used

What I Learned
Reversing a linked list is about careful pointer manipulation:
Always store next before changing curr.next
Update prev and curr properly
Iterative solution is simple and efficient

Final Thought
At first, it felt scary because pointers can be tricky.
Once I visualized prev, curr, and next_node and updated them in order, it became clear and safe.
This is a classic example of iterative pointer-based linked list manipulation.

Top comments (0)