⚡ TL;DR
Solve Reverse Linked List in Swift 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.
func reverseList(_ head: ListNode?) -> ListNode? {
var prev: ListNode? = nil
var curr = head
while let node = curr {
let nxt = node.next
node.next = prev
prev = node
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.
func reverseListRecursive(_ head: ListNode?) -> ListNode? {
guard let head = head, let next = head.next else { return head }
let newHead = reverseListRecursive(next)
next.next = head
head.next = nil
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 Dart
- Reverse Linked List in Go
- Linked List Cycle in Swift
FAQ
What is the best approach to solve Reverse Linked List in Swift?
The recommended approach is Iterative (Optimal), which runs in O(n) time with O(1) space. The full Swift implementation is shown above.
What is the time complexity of Reverse Linked List in Swift?
Using Iterative (Optimal), the time complexity is O(n) and the space complexity is O(1).
Happy coding!
