Reverse Linked List
LeetCode #206 [Easy]
Problem Statement
Given the head of a singly 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
Approach 1: Iterative
Explanation: Use three pointers: prev, curr, next.
Reverse links one by one.
Time Complexity: O(n)
Space Complexity: O(1)
prev = NULL
curr = head
while curr != NULL:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
π‘ Think: Flip each pointer with prevβcurrβnext until the end, returning the last seen node.
Approach 2: Recursive
Explanation: Reverse the rest of the list recursively
and fix pointers.
Time Complexity: O(n)
Space Complexity: O(n) (recursion stack)
if head == NULL or head.next == NULL:
return head
rest = reverse(head.next)
head.next.next = head
head.next = NULL
return rest
π‘ Think: Reverse the rest first, then point head.next back to head and cut head.next.
Solve on LeetCode