206. Reverse Linked List
Asked at 33Apple77Microsoft66Bloomberg64Google59Amazon58Meta51Nokia87TikTok58tcs57Infosys39Luxoft100Yahoo100Zenefits100Zynga100Yelp94X94Qualcomm91Adobe86Snap80SAP73Paytm71Oracle66jio65Visa61ServiceNow55EPAM Systems51Uber50Nvidia48Yandex46Cisco45IBM44Goldman Sachs33LinkedIn20
Problem
Reverse a singly linked list and return the new head.
Example: 1→2→3→4→5 → 5→4→3→2→1
Constraints: follow-up: both iteratively and recursively.
Iteratively flip each next pointer while walking forward.
Complexity: O(n) time, O(1) space (recursive version uses O(n) stack).
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev, cur = None, head
while cur:
cur.next, prev, cur = prev, cur, cur.next
return prev
assert list_vals(Solution().reverseList(make_list([1, 2, 3, 4, 5]))) == [5, 4, 3, 2, 1]
assert Solution().reverseList(None) is None
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null, cur = head;
while (cur != null) {
ListNode nxt = cur.next;
cur.next = prev;
prev = cur;
cur = nxt;
}
return prev;
}
}
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
for cur := head; cur != nil; {
cur.Next, prev, cur = prev, cur, cur.Next
}
return prev
}