Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Reverse a Singly Linked List in Python

Reverse the links in place or build a reversed copy, with runnable Python examples and the time and space costs of each approach.

Table of Contents

To reverse a singly linked list in Python, walk through the nodes and reverse each next reference. Save the original next node before changing the reference so you can continue walking the list. Return the old tail as the new head.

Reverse linked list Picture 1

For example, 0 → 1 → 2 → 3 becomes 3 → 2 → 1 → 0. An empty list returns None, and a one-node list remains a one-node list. These examples assume the input has no cycle.

Reverse the existing nodes in place

Reverse linked list Picture 3
The previous, current, and following references keep both parts of the list reachable.
class Node:
    def __init__(self, value, next_node=None):
        self.value = value
        self.next = next_node


def reverse_in_place(head):
    previous = None
    current = head
    while current is not None:
        following = current.next
        current.next = previous
        previous = current
        current = following
    return previous


head = Node(0, Node(1, Node(2, Node(3))))
head = reverse_in_place(head)
assert head.value == 3
assert head.next.next.next.value == 0
assert head.next.next.next.next is None

At each iteration, previous heads the portion already reversed, and current heads the portion still to process. This takes O(n) time and O(1) auxiliary space. The original head becomes the tail. Callers that still hold a reference to it will see its changed next.

Build a reversed copy instead

Reverse linked list Picture 2
The original illustration shows an intermediate list used to rebuild the nodes.

When the original list must remain usable, allocate new nodes. You can prepend each value as you traverse the original, which creates the same reverse order without an intermediate Python list.

def reversed_copy(head):
    result = None
    current = head
    while current is not None:
        result = Node(current.value, result)
        current = current.next
    return result

The copy takes O(n) time and allocates O(n) new nodes, while sharing references to the values. Use it if other code relies on the original links. For further reading, see the Stanford CS Education Library’s linked-list materials and the Python fundamentals course.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.