Python ProgrammingLevel: Intermediatepython

Reversing a Singly Linked List in Python: Step-by-Step Algorithm

Reviewed by Dr. Alan Myers, Ph.D. in Computer Science.
Free Educational Resource
Problem Statement / Assignment Scope

Given the `head` of a singly linked list, reverse the list in-place and return the reversed list's new head with O(n) time and O(1) space complexity.

Prerequisites: Object-oriented programming in Python, memory references, and pointers.

Step-by-Step Worked Solution

1. Pointer Manipulation Mechanism

To reverse a singly linked list without allocating new nodes in memory, we maintain three pointers: prev, curr, and next_node.

  1. Store curr.next before mutating it to prevent severing the remaining chain.
  2. Redirect curr.next backward to point to prev.
  3. Shift prev and curr one step forward.
solution.pypython
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverse_linked_list(head: ListNode | None) -> ListNode | None:
    """
    Reverses a singly linked list in-place using 3 pointers.
    Time Complexity: O(n)
    Space Complexity: O(1)
    """
    prev = None
    curr = head

    while curr is not None:
        # 1. Save reference to next node
        next_node = curr.next
        # 2. Reverse current node's pointer
        curr.next = prev
        # 3. Step forward
        prev = curr
        curr = next_node

    return prev  # New head of reversed list

Key Takeaways & Core Principles

  • In-place reversal avoids O(n) extra memory allocation.
  • Always store `curr.next` in a temporary variable before changing pointers.
  • Handles edge cases: empty list (`None`) and single-node lists seamlessly.

Frequently Asked Questions

What is the time and space complexity?

Time complexity is O(n) as each node is visited once. Space complexity is O(1) because only pointer variables are allocated.

Academic References & Standards

  • [1]Sedgewick, R., & Wayne, K. (2011). Algorithms (4th ed.). Addison-Wesley. Source Link
Custom Academic Guidance

Need a Custom Solution for Your Specific Assignment?

Our verified Ph.D. subject experts deliver 100% original, rubric-compliant assistance with Turnitin reports and step-by-step explanations.