DEV Community

Samantha Vincent
Samantha Vincent

Posted on

Reverse a Linked List

Reversing a Singly Linked List

Problem

You’re given the head of a singly linked list. The task is to reverse the list and return the new head.


Strategy

Reversing a linked list sounded confusing at first because everything points in one direction.

Instead of thinking about the whole list, I focused on one node at a time:

  • Keep track of the previous node
  • Reverse the current node’s pointer
  • Move forward

So the idea is simple — change the direction step by step.


Code

class Solution:
    def reverseList(self, head):
        prev = None
        current = head

        while current:
            next_node = current.next
            current.next = prev
            prev = current
            current = next_node

        return prev
Enter fullscreen mode Exit fullscreen mode

Key Lines Explained

  • prev = None
    This becomes the new end of the list. Eventually, the original head will point to this.

  • current = head
    Start traversing from the beginning.

  • next_node = current.next
    Save the next node before changing anything. Without this, the rest of the list would be lost.

  • current.next = prev
    This is where the actual reversal happens — the direction of the link is flipped.

  • prev = current
    Move prev forward to keep track of the new head.

  • current = next_node
    Move ahead in the original list.


Why This Works

Each step reverses one link. Over time, the entire list gets reversed without creating any new nodes.

It’s just careful pointer manipulation.


Complexity

  • Time: O(n)
  • Space: O(1)

Final Note

This problem feels tricky until you stop thinking about the whole list.

Once you focus on one node at a time, it becomes a simple, repeatable process.

Top comments (0)