DEV Community

Sri Mahalakshmi
Sri Mahalakshmi

Posted on

Reversing a Linked List Using Iterative Method in Python

Problem Explanation

You are given the head of a singly linked list.
Your task is to reverse the linked list and return the new head.

A linked list looks like:
1 → 2 → 3 → 4 → 5

After reversing:
5 → 4 → 3 → 2 → 1


Method Used: Iterative Approach

Idea

We reverse the direction of each node’s pointer one by one.

For each node:

  • Store next node
  • Reverse the link
  • Move forward

Why This Method?

  • Time complexity: O(n)
  • Space complexity: O(1)
  • Simple and efficient
  • No extra memory used

Python Code with Explanation

class Solution:
    def reverseList(self, head):
Enter fullscreen mode Exit fullscreen mode

Defines the function. head is the starting node.


        prev = None
Enter fullscreen mode Exit fullscreen mode

prev will store the previous node (initially None).


        curr = head
Enter fullscreen mode Exit fullscreen mode

Start from the head of the list.


        while curr:
Enter fullscreen mode Exit fullscreen mode

Loop until we reach the end of the list.


            next_node = curr.next
Enter fullscreen mode Exit fullscreen mode

Store the next node before breaking the link.


            curr.next = prev
Enter fullscreen mode Exit fullscreen mode

Reverse the link (point current node to previous).


            prev = curr
Enter fullscreen mode Exit fullscreen mode

Move prev forward.


            curr = next_node
Enter fullscreen mode Exit fullscreen mode

Move curr forward.


        return prev
Enter fullscreen mode Exit fullscreen mode

At the end, prev becomes the new head.


Complete Code

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

Step-by-Step Example

Input:

1 → 2 → 3 → 4 → 5
Enter fullscreen mode Exit fullscreen mode

Steps:

  • Reverse links one by one
  • Final reversed list

Output:

5 → 4 → 3 → 2 → 1
Enter fullscreen mode Exit fullscreen mode

Key Takeaway

Reversing a linked list is about changing pointer directions, not values. The iterative approach is the most efficient and commonly used method.


Top comments (0)