
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 ): Defines the function. head is the starting node. prev = None prev will store the previous node (initially None). curr = head Start from the head of the list. while curr : Loop until we reach the end of the list. next_node = curr . next Store the next node before breaking the link. curr . next = prev Reverse the link (point current node to previous). prev = curr Move prev forward. curr = next_node Move curr forward. return prev At the end, pre
Continue reading on Dev.to Python
Opens in a new tab


