
Reverse a Linked List β Python (Step-by-Step)
π Reverse a Linked List β Python (Step-by-Step) Hi All, Today I solved a fundamental problem in Data Structures: Reverse a Linked List . π Problem Statement Given the head of a singly linked list , reverse the list and return the new head. π Example Input: 1 -> 2 -> 3 -> 4 -> 5 Output: 5 -> 4 -> 3 -> 2 -> 1 π‘ Approach πΉ Iterative Method (Optimal) π We reverse the links one by one using pointers. π§ Step-by-Step Logic We use three pointers: prev β previous node curr β current node next_node β next node Steps: Initialize: prev = None curr = head Traverse the list: Store next node Reverse link Move pointers forward π» Python Code class ListNode : def __init__ ( self , val = 0 ): self . val = val self . next = None def reverseList ( head ): prev = None curr = head while curr : next_node = curr . next # store next curr . next = prev # reverse link prev = curr # move prev curr = next_node # move curr return prev π Dry Run For: 1 -> 2 -> 3 Steps: Reverse 1 β None Reverse 2 β 1 Reverse 3 β 2 β 1
Continue reading on Dev.to
Opens in a new tab


