Back to articles
Reverse a Linked List

Reverse a Linked List

via Dev.to BeginnersChristina Sharon S

Introduction Linked Lists are a fundamental data structure, and one of the most important operations is reversing a linked list . This problem helps you understand pointer manipulation, which is essential for mastering linked lists. Problem Statement Given the head of a linked list, reverse the list and return the new head. Example Input: 1 → 2 → 3 → 4 → 5 → NULL Output: 5 → 4 → 3 → 2 → 1 → NULL Intuition In an array, reversing is easy because we can access elements by index. But in a linked list: We only move forward So we must change the direction of links Key Idea We reverse the links by changing: current.next → previous Approach (Iterative) We use three pointers: prev → previous node curr → current node next_node → store next node Steps Initialize: prev = None curr = head Traverse the list: Store next node Reverse the link Move pointers forward Python Implementation class ListNode : def __init__ ( self , val = 0 , next = None ): self . val = val self . next = next def reverseList (

Continue reading on Dev.to Beginners

Opens in a new tab

Read Full Article
8 views

Related Articles