You are given the head
of a singly linked list. Your task is to reverse the list and return the new head of the reversed list.
Details:
Examples:
head = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
head = [1, 2]
Output: [2, 1]
head = []
(empty list)
Output: []
Constraints:
[0, 5000]
.-5000 <= Node.val <= 5000
Could you provide an efficient algorithm to reverse the linked list? Consider both iterative and recursive solutions. What are the time and space complexities of your solutions? Also, consider any edge cases and how your algorithm handles them.
Given the head of a singly linked list, reverse the list and return the reversed list.
A naive approach to reversing a singly linked list involves creating a new linked list by iterating through the original list and adding each element to the beginning of the new list. This effectively reverses the order of the elements.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseListNaive(head):
new_head = None
current = head
while current:
new_node = ListNode(current.val)
new_node.next = new_head
new_head = new_node
current = current.next
return new_head
The optimal approach reverses the linked list in-place, meaning without using extra space proportional to the input size. This can be done iteratively by changing the next
pointers of each node.
prev
to None
and current
to head
.next_node
.next
pointer of the current
node to point to prev
.prev
to current
and current
to next_node
.prev
will be the new head of the reversed list.class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
Another optimal approach is using recursion.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseListRecursive(head):
if not head or not head.next:
return head
new_head = reverseListRecursive(head.next)
head.next.next = head
head.next = None
return new_head
head
is None
), the function should return None
.The optimal approach for reversing a singly linked list is the iterative in-place reversal, which has a time complexity of O(n) and a space complexity of O(1). The recursive approach also has a time complexity of O(n) but uses O(n) space due to the call stack. The naive approach uses O(n) time and O(n) space. It's crucial to handle edge cases such as an empty list or a single-node list correctly.