Problem Explanation
You are given the head of a singly linked list.
Your task is to reverse the linked list and return the new head.
A linked list looks like:
1 → 2 → 3 → 4 → 5
After reversing:
5 → 4 → 3 → 2 → 1
Method Used: Iterative Approach
Idea
We reverse the direction of each node’s pointer one by one.
For each node:
- Store next node
- Reverse the link
- Move forward
Why This Method?
- Time complexity:
O(n) - Space complexity:
O(1) - Simple and efficient
- No extra memory used
Python Code with Explanation
class Solution:
def reverseList(self, head):
Defines the function. head is the starting node.
prev = None
prev will store the previous node (initially None).
curr = head
Start from the head of the list.
while curr:
Loop until we reach the end of the list.
next_node = curr.next
Store the next node before breaking the link.
curr.next = prev
Reverse the link (point current node to previous).
prev = curr
Move prev forward.
curr = next_node
Move curr forward.
return prev
At the end, prev becomes the new head.
Complete Code
class Solution:
def reverseList(self, head):
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
Step-by-Step Example
Input:
1 → 2 → 3 → 4 → 5
Steps:
- Reverse links one by one
- Final reversed list
Output:
5 → 4 → 3 → 2 → 1
Key Takeaway
Reversing a linked list is about changing pointer directions, not values. The iterative approach is the most efficient and commonly used method.
Top comments (0)