
Reverse a Linked List
Introduction Reversing a linked list is one of the most common problems in data structures. It helps in understanding pointers and linked list traversal. Problem Statement Given the head of a singly linked list, reverse the list and return the new head. Approach (Iterative Method) We can reverse the linked list using three pointers: Initialize: prev = None current = head Traverse the list: Store next node Reverse the link Move prev and current forward Continue until current becomes None Return prev as new head Python Code python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def reverseList(head): prev = None current = head while current: next_node = current.next current.next = prev prev = current current = next_node return prev ## Input 1 -> 2 -> 3 -> 4 -> 5 ## ouput 5-> 4-> 3-> 2-> 1
Continue reading on Dev.to Python
Opens in a new tab

