Reverse Linked List
Given the head of a singly linked list, reverse the list and return the new head.
Write a function that reverses a singly linked list. The function should take the head node and return the new head of the reversed list.
How to Solve
Use iterative approach with three pointers: prev, current, and next. Traverse the list, reversing the next pointer of each node to point to the previous node. Alternatively, use recursion to reverse from the end.
Code
Test Cases
Input 1
Expected Output: 5 -> 4 -> 3 -> 2 -> 1 (reversed list)
Input 2
Expected Output: 2 -> 1 (reversed list)
Input 3
Expected Output: null
Complexity
Time Complexity: O(n) - We traverse the list once, visiting each node exactly once.
Space Complexity: O(1) - Iterative approach uses only constant extra space. Recursive approach uses O(n) space for the call stack.