Reverse a Doubly Linked List in DSA Python - Time & Space Complexity
We want to understand how the time needed to reverse a doubly linked list changes as the list grows.
Specifically, how does the number of steps grow when the list gets longer?
Analyze the time complexity of the following code snippet.
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
def reverse_doubly_linked_list(head):
current = head
while current:
current.prev, current.next = current.next, current.prev
head = current
current = current.prev
return head
This code reverses the links of a doubly linked list so the last node becomes the first.
- Primary operation: The while loop that visits each node once.
- How many times: Exactly once per node, so n times for n nodes.
As the list grows, the number of steps grows directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The steps increase in a straight line as the list gets longer.
Time Complexity: O(n)
This means the time to reverse the list grows directly with the number of nodes.
[X] Wrong: "Reversing a doubly linked list takes more than linear time because of the two pointers per node."
[OK] Correct: Each node is visited once, and swapping two pointers is a constant time action, so overall time is still linear.
Understanding this helps you explain how linked list operations scale, a common topic in interviews.
"What if we tried to reverse the list using recursion instead of a loop? How would the time complexity change?"