Problem Number: 206 Difficulty: Easy Category: Linked List, Recursion LeetCode Link: https://leetcode.com/problems/reverse-linked-list/
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
- The number of nodes in the list is the range
[0, 5000]. -5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both solutions?
I used an Iterative approach with three pointers to reverse the linked list. The key insight is to use three pointers (prev, curr, next) to reverse the links one by one.
Algorithm:
- Initialize prev to None and curr to head
- While curr is not None:
- Store next node (curr.next)
- Reverse the link (curr.next = prev)
- Move prev to curr
- Move curr to next
- Return prev (new head)
The solution uses iterative approach with three pointers to reverse the linked list. See the implementation in the solution file.
Key Points:
- Uses three pointers: prev, curr, next
- Reverses links one by one
- Handles empty list case
- Returns new head (prev)
- Simple and efficient approach
Time Complexity: O(n)
- Single pass through the linked list
- Each node is visited once
- Total: O(n)
Space Complexity: O(1)
- Uses only a constant amount of extra space
- No additional data structures needed
-
Three Pointers: Using prev, curr, and next pointers simplifies the reversal.
-
Link Reversal: Each iteration reverses one link: curr.next = prev.
-
Pointer Movement: Moving pointers in the correct order is crucial.
-
New Head: The new head is the last node (prev after loop ends).
-
Empty List: Handles empty list case naturally.
-
Single Node: Works correctly for single node lists.
-
Wrong Pointer Order: Initially might move pointers in wrong order.
-
Lost References: Not storing next node before changing curr.next.
-
Complex Logic: Overcomplicating the pointer manipulation.
-
Wrong Return: Returning wrong pointer as new head.
- Reverse Linked List II (Problem 92): Reverse portion of linked list
- Palindrome Linked List (Problem 234): Check if linked list is palindrome
- Add Two Numbers (Problem 2): Add numbers represented by linked lists
- Merge Two Sorted Lists (Problem 21): Merge sorted linked lists
- Recursive: Use recursion to reverse list - O(n) time, O(n) space
- Stack-based: Use stack to reverse order - O(n) time, O(n) space
- Array-based: Convert to array, reverse, rebuild - O(n) time, O(n) space
- Wrong Pointer Order: Moving pointers in incorrect order.
- Lost References: Not storing next node before changing links.
- Complex Logic: Overcomplicating the pointer manipulation.
- Wrong Return: Returning wrong pointer as new head.
- Empty List: Not handling empty list case properly.
Note: This is a classic linked list problem that demonstrates efficient iterative reversal with three pointers.