Skip to main content

Reverse a Singly Linked List in Java and Python

Reverse a singly linked list in place with three references, O(n) time, and O(1) extra space in Java and Python.

Problem and input contract

Pass the head of a finite, acyclic list of nodes with a value and a next reference. The function rewires the original nodes and returns the new head.

1 → 2 → 3 becomes 3 → 2 → 1. An empty list returns null or None. The list 8 returns the same node.

Worked example

1 → 2 → 3 becomes 3 → 2 → 1.

At node 1, save node 2 before pointing 1 to null. At node 2, save node 3 before pointing 2 back to 1. At node 3, point it back to 2. The saved following reference is null, so return 3.

How the solution works

Save the next node before reversing its pointer. The previous pointer leads to the reversed prefix and current leads to the unprocessed suffix.

The temporary following variable preserves the only link to the remaining nodes. The loop changes the original list, so callers should keep the returned head.

Python solution

class Node:
    def __init__(self, value, next_node=None):
        self.value = value
        self.next = next_node


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

Java solution

class Solution {
    static class Node {
        int value;
        Node next;
        Node(int value) { this.value = value; }
    }
    static Node reverseList(Node head) {
        Node previous = null;
        Node current = head;
        while (current != null) {
            Node following = current.next;
            current.next = previous;
            previous = current;
            current = following;
        }
        return previous;
    }
}

Approaches and complexity

A stack can store all n node references and reconnect them in reverse order, at the cost of O(n) extra space. The iterative solution visits each node once and uses three references. A recursive reversal also takes O(n) time and uses O(n) stack space.

Approach comparison
ApproachTimeAuxiliary spaceAdvantageLimitationUse case
StackO(n)O(n)Explicit reverse orderStores every referenceWhen a stack is already available
Three referencesO(n)O(1)Reuses nodesMutates the listIn-place reversal

Common mistakes and interview follow-up

Save the next node before changing current.next. Update your head reference with the returned node. Duplicate values require no special handling because the algorithm moves links.

Related practice: Find children of a given binary tree by target node or by target value.

Comments

Popular posts from this blog

Minimum Window Substring: Efficient Algorithm for Finding the Shortest Substring

The Minimum Window Substring problem is a classic string manipulation challenge that tests our algorithmic skills. In this blog, we will explore an efficient solution to find the minimum window substring in a given string. We will provide implementation examples in both Java and Python, enabling you to grasp the concepts and apply them to your own coding projects.   Understanding the Problem: Given a string and a target pattern, our objective is to find the minimum window substring in the given string that contains all the characters of the target pattern. The minimum window substring refers to the shortest possible substring that satisfies this condition.   Approach: To solve the Minimum Window Substring problem, we can use the sliding window technique. This approach involves maintaining a window of characters in the string and adjusting its size based on certain conditions. The key steps of the algorithm are as follows: Create two pointers, left and right, to define the windo...

Longest Palindromic Substring: Explained with Java and Python Code

The Longest Palindromic Substring problem is a classic challenge in the realm of string manipulation. In this blog, we will delve into the intricacies of finding the longest palindromic substring in a given string. Through a step-by-step approach and illustrative examples, you will gain a comprehensive understanding of the problem and learn how to solve it efficiently.   Understanding the Problem: A palindrome is a string that reads the same forward and backward. The Longest Palindromic Substring problem requires finding the longest substring within a given string that is also a palindrome. Our goal is to determine the length of this substring and return the substring itself.   Approach: To solve the Longest Palindromic Substring problem, we can employ a dynamic programming approach or use the expanding around center technique. Here, we will explore the dynamic programming approach. Create a boolean table, dp, of size [n][n] (where n is the length of the input string) to store ...