Reverse a linked list
Company: LinkedIn
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of linked list data structures and proficiency manipulating pointers or references to perform in-place transformations when reversing a linked list. Commonly asked in Coding & Algorithms interviews, it gauges algorithmic thinking and practical application-level competency in list operations rather than purely conceptual theory.
Constraints
- 0 <= n <= 100000 where n is the number of nodes
- -10^9 <= Node.val <= 10^9
- Must run in O(n) time
- Use O(1) extra space
- head may be None (empty list)
Solution
def reverse_list(head):
prev = None
curr = head
while curr is not None:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
Explanation
Time complexity: O(n). Space complexity: O(1).
Hints
- Maintain three pointers: prev, curr, next.
- Iteratively set curr.next = prev, then advance all pointers.
- A recursive solution is possible: reverse the rest, then set head.next.next = head and head.next = None.