⚡ TL;DR
Solve Reverse Linked List in Dart with working code. Iterative (Optimal) approach with O(n) time, plus complexity analysis and interview tips.
Reverse Linked List (#206 — Easy): Given the head of a singly linked list, reverse the list, and return the reversed list.
Problem Statement
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]Approach: Iterative (Optimal)
Time: O(n) | Space: O(1)
Three pointers dance: save next, flip current’s pointer backward, advance both. The head becomes the tail and prev ends up as the new head.
ListNode? reverseList(ListNode? head) {
ListNode? prev, curr = head;
while (curr != null) {
var nxt = curr.next;
curr.next = prev;
prev = curr;
curr = nxt;
}
return prev;
}Approach: Recursive
Time: O(n) | Space: O(n) (call stack)
Recursively reverse the rest of the list, then fix the current node. Elegant but uses stack space proportional to list length.
ListNode? reverseListRecursive(ListNode? head) {
if (head == null || head.next == null) return head;
var newHead = reverseListRecursive(head.next);
head.next!.next = head;
head.next = null;
return newHead;
}Key Takeaways
- Start with the brute-force approach to understand the problem
- Iterative (Optimal) gives the optimal O(n) solution
- Practice this pattern — it appears frequently in coding interviews
Related Problems
- Reverse Linked List in Python
- Reverse Linked List in Go
- Reverse Linked List in Swift
- Linked List Cycle in Dart
FAQ
What is the best approach to solve Reverse Linked List in Dart?
The recommended approach is Iterative (Optimal), which runs in O(n) time with O(1) space. The full Dart implementation is shown above.
What is the time complexity of Reverse Linked List in Dart?
Using Iterative (Optimal), the time complexity is O(n) and the space complexity is O(1).
Happy coding!
