Problem
Given thehead of a singly linked list, reverse the list, and return the reversed list.
Examples
Constraints
- The number of nodes in the list is the range
[0, 5000]. -5000 <= Node.val <= 5000
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 206 with 15 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 206 # by problem number
lcpy gen -s reverse_linked_list # by problem name
head of a singly linked list, reverse the list, and return the reversed list.
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Input: head = [1,2]
Output: [2,1]
Input: head = []
Output: []
[0, 5000].-5000 <= Node.val <= 5000from leetcode_py import ListNode
class Solution:
# Time: O(n)
# Space: O(1)
def reverse_list(self, head: ListNode[int] | None) -> ListNode[int] | None:
if not head:
return None
# Iterative approach using three pointers
# Example: [1,2,3] -> [3,2,1]
#
# Initial: prev curr
# None ↓
# 1 -> 2 -> 3 -> None
#
prev: ListNode[int] | None = None
curr: ListNode[int] | None = head
while curr:
# Store next node before breaking the link
next_node = curr.next
#
# prev curr next_node
# None ↓ ↓
# 1 -> 2 -> 3 -> None
#
# Reverse the current link
curr.next = prev
# None <- 1 2 -> 3 -> None
# prev curr next_node
#
# Move pointers forward
prev = curr
curr = next_node
# 1 <- 2 3 -> None
# prev curr
#
# 1 <- 2 <- 3 None
# prev curr
# prev now points to new head of reversed list
return prev
| Time | Space |
|---|---|
| O(n) | O(1) |