Problem Statement:
Given the head of a linked list, reverse the list and return the new head.
Example:
Input: 1 → 2 → 3 → 4 → 5
Output: 5 → 4 → 3 → 2 → 1
Approach:
We traverse the list and reverse the direction of links using three pointers:
- previous node
- current node
- next node Code:
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
Explanation:
Each node’s next pointer is reversed to point to the previous node. At the end, the previous pointer becomes the new head.
Time Complexity:
O(n)
Space Complexity:
O(1)
Top comments (0)