The Reverse Linked List problem requires reversing the direction of all links in a singly linked list so that the last node becomes the first node.

Problem

Given the head of a singly linked list, reverse the list and return the new head. The links between the nodes must be reversed without creating a separate linked list.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

head = [1,2,3,4,5] 

Output

[5,4,3,2,1] 

Solution

This solution uses three pointers: prev, current, and next. The prev pointer stores the previously processed node, while current points to the node currently being processed.

For each node, the next node is temporarily stored so that the remaining list is not lost. The next pointer of the current node is then reversed to point to prev.

Finally, both pointers are moved forward and the process continues until all nodes have been processed. After the traversal, prev points to the new head of the reversed list.
public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    ListNode current = head;

    while (current != null) {
        ListNode next = current.next;
        current.next = prev;
        prev = current;
        current = next;
    }
    return prev;
}

Complexity

The algorithm traverses every node exactly once, resulting in a time complexity of O(n). The list is reversed in-place using only a few pointers, so the extra space complexity is O(1).
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion