DEV Community

Anjana R.K.
Anjana R.K.

Posted on • Edited on

Reverse a Linked List

Hi everyone!
Today I solved one of the most common linked list problems — reversing a linked list. It looks tricky at first, but the logic is actually simple once you understand pointers.

Problem
Given the head of a singly linked list, reverse it and return the new head.

Example:
Input: 1 -> 2 -> 3 -> 4

Output: 4 -> 3 -> 2 -> 1

My Approach

At first, I found it confusing because changing links can break the list.
Then I understood:

We need to carefully reverse the direction of pointers one by one.

Logic
Use three pointers:
prev - previous node
curr - current node
next_node - store next node
Reverse the link:
Point current node to previous
Move all pointers forward

Code (Python)
class Solution:
def reverseList(self, head):
prev = None
curr = head

    while curr:
        next_node = curr.next
        curr.next = prev
        prev = curr
        curr = next_node

    return prev
Enter fullscreen mode Exit fullscreen mode

Time & Space Complexity
Time: O(n)
Space: O(1)

Key Insight
We must store the next node before changing links, otherwise we lose the remaining list.

What I Learned
Pointer manipulation is very important in linked lists
Always store next node before modifying links
This is a fundamental interview problem

Thanks for reading!
Feel free to share other approaches like recursive solution.

Top comments (0)