As asked
Given the definition of a singly linked list node in Swift, write a function that reverses the list in place and returns the new head. What is the time and space complexity?
Sample answer outline
A strong answer uses three pointers (prev, current, next), iterates once, reversing the next pointer at each node. Time O(n), space O(1). Candidate should handle nil input and single-node input without special cases.
Reference implementation (swift)
class ListNode {
var val: Int
var next: ListNode?
init(_ val: Int) { self.val = val }
}
func reverseList(_ head: ListNode?) -> ListNode? {
// implement here
}Expect these follow-ups
- How would you detect a cycle in the same list structure?
- Can you write a recursive version and what are its stack depth risks for a long list?