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