0
0
DSA Pythonprogramming~5 mins

Reverse a Doubly Linked List in DSA Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Reverse a Doubly Linked List
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: The while loop that visits each node once.
  • How many times: Exactly once per node, so n times for n nodes.
How Execution Grows With Input

As the list grows, the number of steps grows directly with the number of nodes.

Input Size (n)Approx. Operations
10About 10 steps
100About 100 steps
1000About 1000 steps

Pattern observation: The steps increase in a straight line as the list gets longer.

Final Time Complexity

Time Complexity: O(n)

This means the time to reverse the list grows directly with the number of nodes.

Common Mistake

[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.

Interview Connect

Understanding this helps you explain how linked list operations scale, a common topic in interviews.

Self-Check

"What if we tried to reverse the list using recursion instead of a loop? How would the time complexity change?"