DEV Community

Dharani
Dharani

Posted on

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:

  1. Initialize:

    • prev = None
    • current = head
  2. Traverse the list:

    • Store next node
    • Reverse the link
    • Move prev and current forward
  3. Continue until current becomes None

  4. 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



Enter fullscreen mode Exit fullscreen mode

Top comments (0)