Reverse Linked List
Given the head of a singly linked list, reverse the list, and return the reversed list.
Examples
head = [1,2,3,4,5]
[5,4,3,2,1]
The linked list is reversed.
head = [1,2]
[2,1]
The linked list is reversed.
Constraints
- •
The number of nodes in the list is [0, 5000] - •
-5000 <= Node.val <= 5000
Approaches
Traverse the list, store values in an array, and create a new reversed list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_list(head):
values = []
curr = head
while curr:
values.append(curr.val)
curr = curr.next
dummy = ListNode(0)
curr = dummy
for val in reversed(values):
curr.next = ListNode(val)
curr = curr.next
return dummy.nextUse three pointers to reverse the links between nodes.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_list(head):
prev = None
curr = head
while curr:
next_temp = curr.next
curr.next = prev
prev = curr
curr = next_temp
return prevRecursively reverse the rest of the list, then fix the current node's pointer.
Diagram
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_list(head):
if not head or not head.next:
return head
new_head = reverse_list(head.next)
head.next.next = head
head.next = None
return new_headComplexity Comparison
| Approach | Time | Space | Description |
|---|---|---|---|
| Iterative with Extra Space | O(n) | O(n) | Traverse the list, store values in an array, and create a new reversed list. |
| Iterative - Three Pointers | O(n) | O(1) | Use three pointers to reverse the links between nodes. |
| Recursive | O(n) | O(n) | Recursively reverse the rest of the list, then fix the current node's pointer. |
Traverse the list, store values in an array, and create a new reversed list.
Use three pointers to reverse the links between nodes.
Recursively reverse the rest of the list, then fix the current node's pointer.
Common Mistakes
Losing reference to the next node before updating the current node's pointer
Not returning the correct new head of the reversed list
Creating a cycle by not setting the last node's next to None