Reverse Linked List
LeetCode 206 · View on LeetCode
Iteratively reverse by maintaining a previous pointer. At each step, save next, point current to previous, then advance both pointers.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_list(head: ListNode | None) -> ListNode | None:
prev = None
curr = head
while curr:
curr.next, prev, curr = prev, curr, curr.next
return prev
def to_list(head: ListNode | None) -> list[int]:
result = []
while head:
result.append(head.val)
head = head.next
return result
def from_list(vals: list[int]) -> ListNode | None:
dummy = ListNode()
curr = dummy
for v in vals:
curr.next = ListNode(v)
curr = curr.next
return dummy.next
if __name__ == '__main__':
print(to_list(reverse_list(from_list([1, 2, 3, 4, 5])))) # [5, 4, 3, 2, 1]
print(to_list(reverse_list(from_list([1, 2])))) # [2, 1]
print(to_list(reverse_list(from_list([])))) # []