Taro Logo

Reverse Linked List

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+26
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.4K views
Topics:
Linked ListsRecursion

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

Constraints:

  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the input linked list is empty (i.e., the head is null)?
  2. Can I assume the linked list fits entirely in memory, or should I consider any stream-based or external memory constraints?
  3. Are the node values constrained to a specific data type, such as 32-bit integers, or could they be arbitrary objects or strings?
  4. Should the reversal be performed strictly in-place with $O(1)$ extra space, or is allocating a new linked list acceptable?
  5. Does the singly linked list contain any cycles, or can I assume it is always a proper acyclic list?

Brute Force Solution

Approach

Imagine you have a line of people holding hands in a specific order, and you want to turn the whole line around so that the person at the very end is now at the very front, facing the opposite direction. A brute force way to solve this is to completely dismantle the original line, inspect every single person one by one, and build a brand new line from scratch in the reverse order.

Here's how the algorithm would work step-by-step:

  1. Walk down the original line of people from the very beginning to the very end, taking note of each person.
  2. Write down or memorize the exact sequence of people in the order you encounter them.
  3. Take a completely fresh piece of paper or a new workspace to build your reversed line.
  4. Go back to your remembered sequence and pick the person who was standing at the very end of the original line.
  5. Place this last person as the first person in your new workspace.
  6. Find the person who was standing right before the end in the original line, and place them second in your new workspace.
  7. Repeat this process by working your way backward through your memory of the original line until every single person has been moved to the new line in the exact opposite order.

Code Implementation

class ListNode:
    def __init__(self, val=0, next_node=None):
        self.val = val
        self.next = next_node

def reverse_linked_list_brute(head_node):
    # We extract all node values into an array to simulate dismantling the line and storing the sequence
    node_values = []
    current_node = head_node
    while current_node is not None:
        node_values.append(current_node.val)
        current_node = current_node.next

    # If the original list is empty, we immediately return None as there is nothing to reverse
    if not node_values:
        return None

    # We build a brand new linked list by iterating backwards through our remembered sequence
    new_head_node = ListNode(node_values[-1])
    current_new_node = new_head_node
    for index in range(len(node_values) - 2, -1, -1):
        current_new_node.next = ListNode(node_values[index])
        current_new_node = current_new_node.next

    return new_head_node

Big(O) Analysis

Time Complexity
O(n) – The input size n represents the total number of people in the original linked list. To execute the described brute force approach, we first walk down the entire line of n people to memorize their sequence. Next, we iterate through our memory of all n people in reverse to construct the new workspace. Adding these two sequential passes together results in approximately 2n total operations. By dropping the constant factor, the time complexity simplifies to O(n).
Space Complexity
O(N) – The plain English explanation describes gathering and memorizing the sequence of people and building a completely fresh line in a new workspace. This requires auxiliary data structures, such as a temporary list or array to store the sequence of all N nodes, as well as pointers for the new workspace. As the input size N grows, the memory consumed by these new collections scales directly and linearly with it. Therefore, the total extra memory simplifies to Big O notation of O(N).

Optimal Solution

Approach

Imagine a chain of people holding hands, where each person can only see the person immediately behind them. To reverse the chain efficiently, we can walk down the line and turn each person around one by one, making sure they now point back to the person who was just in front of them.

Here's how the algorithm would work step-by-step:

  1. Stand at the very front of the line of people.
  2. Keep track of the person immediately behind you so you do not lose the rest of the chain as you make changes.
  3. Tell the current person to let go of their original connection and instead grab onto the person who was standing right in front of them.
  4. Step forward to take the place of the person you just adjusted, moving deeper into the line.
  5. Repeat this turning action for every single person in the chain.
  6. Stop once you have reached the absolute end of the original line, meaning everyone has been turned around to face backward.
  7. The person who used to be at the very end of the line is now safely at the front, successfully reversing the entire order.

Code Implementation

class ListNode:
    def __init__(self, value_item=0, next_pointer=None):
        self.value_item = value_item
        self.next_pointer = next_pointer

def reverse_linked_list(head_node):
    previous_node = None
    current_node = head_node

    # We traverse the entire list node by node until we reach the end.
    while current_node is not None:

        next_node_in_line = current_node.next_pointer

        # We redirect the current pointer backwards to reverse the chain.
        current_node.next_pointer = previous_node

        previous_node = current_node
        current_node = next_node_in_line

    # The previous pointer ends up at the new head of the reversed list.
    return previous_node

Big(O) Analysis

Time Complexity
O(n) – As we walk down the line of n people representing the nodes in the linked list, we perform a constant number of pointer manipulation steps for each individual person. We visit every single node exactly once from the head to the very end of the original chain. This means the total operations grow directly proportional to the input size n. Therefore, the overall time complexity simplifies to O(n).
Space Complexity
O(1) – The iterative reversal process relies solely on a constant number of pointer variables to track the current node, the previous node, and the next node. Because no auxiliary data structures, temporary lists, or recursive call stacks are created, the memory footprint remains entirely fixed regardless of the input size N. Therefore, the algorithm achieves an optimal auxiliary space complexity of O(1) by operating entirely in place.

Edge Cases

Empty list where head is null
How to Handle:
The iterative and recursive approaches check for a null head upfront and immediately return null without attempting any pointer manipulation.
Single node linked list
How to Handle:
The algorithm detects that the next pointer is null, skips the reversal loop, and correctly returns the single node as the new head.
Two node linked list
How to Handle:
The standard pointer swapping logic reverses the single link between the two nodes and updates the head to point to the second node.
Very long linked lists causing recursion depth limits
How to Handle:
Using an iterative approach instead of a recursive one avoids call stack overflow errors on excessively long lists.
Nodes with negative values or extreme data boundaries
How to Handle:
Because the algorithm only manipulates the next pointers and ignores node values, any data type or range is handled safely.
Cyclic linked lists where a node points back to a previous node
How to Handle:
A standard reversal on a cyclic list without cycle detection will result in an infinite loop, requiring cycle detection or careful constraint assumptions.
0/75 completed