In this problem, I was given the head of a singly linked list and asked to reverse it.
At first, it didn’t feel very difficult, but I quickly realized that linked lists behave very differently from arrays. There is no direct indexing, so everything depends on how nodes are connected.
Problem Statement
Given the head of a singly linked list
Reverse the list
Return the new head
My Initial Thought
My first idea was simple:
Store all elements in an array
Reverse the array
Rebuild the linked list
This works, but it uses extra space and feels unnecessary.
So I started thinking if I could do it directly by changing the links between nodes.Each node in a linked list points to the next node.
To reverse the list, I don’t need to change the data.
I just need to reverse the direction of the pointers.
Optimized Iterative Approach
I used three pointers to keep track of nodes while traversing:
prev → keeps track of the previous node
curr → current node being processed
next → stores the next node temporarily
Initialize:
prev = null
curr = head
Traverse the list:
Store next node → next = curr.next
Reverse link → curr.next = prev
Move prev forward → prev = curr
Move curr forward → curr = next
At the end:
prev will be the new head of the reversed list
Algorithm
def reverseList(self, head):
prev = None
curr = head
while curr is not None:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
The Code to create an linkedlist and insert elements and return the reversed linked list is given by:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
temp = self.head
while temp.next:
temp = temp.next
temp.next = new_node
def display(self):
temp = self.head
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("None")
def reverse(self):
prev = None
curr = self.head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
self.head = prev
ll = LinkedList()
ll.insert(1)
ll.insert(2)
ll.insert(3)
ll.insert(4)
ll.insert(5)
print("Original List:")
ll.display()
ll.reverse()
print("Reversed List:")
ll.display()
Top comments (0)