Given the head of a singly linked list, reverse the links between nodes and return the new head.
Example:
Input:
1 → 2 → 3 → 4 → 5 → None
Output:
5 → 4 → 3 → 2 → 1 → None
Notice that we don't need to change the values inside the nodes. We only need to change the direction of their next pointers.
The important signal is reversing the direction of each next pointer.
We use three pointers:
prev: The previous node, which will become the current node's next node.curr: The node we're currently processing.nxt: A temporary pointer that saves the next node before we reverse the link.Why do we need nxt? Because if we overwrite curr.next before saving it, we lose access to the rest of the original list.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode | None) -> ListNode | None:
# Step 1: Initialize two pointers.
# prev = None because the new tail must point to None.
# curr = head because we start reversing from the first node.
#
# Example:
# 1 -> 2 -> 3 -> None
#
# prev = None
# curr = Node(1)
prev = None
curr = head
# Step 2: Traverse the linked list until there are no nodes left.
while curr:
# Step 3: Save the next node before reversing the pointer.
#
# Example:
# prev = None
# curr = Node(1)
# curr.next = Node(2)
#
# nxt = Node(2)
# We save Node(2) so we don't lose access to the rest of the list.
nxt = curr.next
# Step 4: Reverse the current node's pointer.
#
# Before:
# None 1 -> 2 -> 3 -> None
# curr
#
# After:
# None <- 1 2 -> 3 -> None
# curr nxt
#
# curr.next now points to prev instead of the original next node.
curr.next = prev
# Step 5: Move prev forward to the current node.
#
# Example:
# prev = Node(1)
#
# Reversed portion:
# None <- 1
# prev
prev = curr
# Step 6: Move curr forward using the saved next node.
#
# Example:
# curr = Node(2)
#
# The remaining list is:
# 2 -> 3 -> None
#
# We continue reversing from Node(2).
curr = nxt
# Step 7: Return the new head.
#
# Example:
# Original: 1 -> 2 -> 3 -> None
# Reversed: 3 -> 2 -> 1 -> None
#
# prev now points to Node(3), the new head.
return prev
# Time Complexity: O(n)
# We visit every node exactly once.
#
# Space Complexity: O(1)
# We use only three pointers: prev, curr, and nxt.