# Reversing a Singly Linked List ## Implementation ```python class ListNode: """Node class for a singly linked list.""" def __init__(self, value=0, next=None): self.value = value self.next = next def reverse_linked_list(head: ListNode) -> ListNode: """ Reverse a singly linked list. Args: head: The head node of the singly linked list. Returns: The new head node of the reversed linked list. Example: >>> # Build list: 1 -> 2 -> 3 -> 4 -> 5 >>> nodes = [ListNode(i) for i in range(1, 6)] >>> for i in range(len(nodes) - 1): ... nodes[i].next = nodes[i + 1] >>> reversed_head = reverse_linked_list(nodes[0]) >>> # reversed_head now points to 5 -> 4 -> 3 -> 2 -> 1 """ if head is None or head.next is None: return head prev = None current = head while current is not None: next_node = current.next # Save next node current.next = prev # Reverse the link prev = current # Move prev forward current = next_node # Move current forward return prev # prev is now the new head def print_linked_list(head: ListNode) -> str: """Helper to print a linked list for testing.""" values = [] current = head while current is not None: values.append(str(current.value)) current = current.next return " -> ".join(values) # --- Testing --- if __name__ == "__main__": # Build list: 1 -> 2 -> 3 -> 4 -> 5 nodes = [ListNode(i) for i in range(1, 6)] for i in range(len(nodes) - 1): nodes[i].next = nodes[i + 1] print("Original:", print_linked_list(nodes[0])) reversed_head = reverse_linked_list(nodes[0]) print("Reversed:", print_linked_list(reversed_head)) # Edge cases print("Empty:", print_linked_list(reverse_linked_list(None))) single = ListNode(42) print("Single:", print_linked_list(reverse_linked_list(single))) ``` ## How It Works The algorithm uses **three pointers** to reverse the list in-place: | Pointer | Role | |---------|------| | `prev` | Points to the already-reversed portion (starts as `None`) | | `current` | Points to the node being processed | | `next_node` | Temporarily saves the next node before reversing the link | ### Step-by-step walkthrough (list `1 → 2 → 3`): ``` Step 1: prev=None, current=1, next_node=2 → 1.next = None, prev=1, current=2 Step 2: prev=1, current=2, next_node=3 → 2.next = 1, prev=2, current=3 Step 3: prev=2, current=3, next_node=None → 3.next = 2, prev=3, current=None Return prev (= 3) → 3 → 2 → 1 ``` ## Complexity | Metric | Value | |--------|-------| | **Time** | O(n) — single pass through the list | | **Space** | O(1) — only three pointer variables used | ## Key Points - **In-place**: No extra nodes or lists are created; links are simply reversed. - **Handles edge cases**: Empty list (`None`) and single-node lists return immediately. - **No recursion**: Avoids stack overflow risk for very long lists.