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:
[0, 5000].-5000 <= Node.val <= 5000Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
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:
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:
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_nodeImagine 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:
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| Case | How to Handle |
|---|---|
| Empty list where head is null | The iterative and recursive approaches check for a null head upfront and immediately return null without attempting any pointer manipulation. |
| Single node linked list | 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 | 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 | 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 | 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 | A standard reversal on a cyclic list without cycle detection will result in an infinite loop, requiring cycle detection or careful constraint assumptions. |