0
0
DSA Pythonprogramming

Insert at Specific Position in Doubly Linked List in DSA Python

Choose your learning style9 modes available
Mental Model
A doubly linked list lets you move forward and backward through nodes. To insert at a position, you find that spot and link the new node between neighbors.
Analogy: Imagine a train with cars connected front and back. To add a new car in the middle, you disconnect the two cars at that spot and connect the new car between them.
null ← 1 ↔ 2 ↔ 3 -> null
Positions:    1    2    3
Dry Run Walkthrough
Input: list: 1 ↔ 2 ↔ 3, insert value 4 at position 2
Goal: Insert the value 4 between nodes 1 and 2, making it the new second node
Step 1: Create new node with value 4
null ← 1 ↔ 2 ↔ 3 -> null, new_node=4 (isolated)
Why: We need a new node ready to insert
Step 2: Traverse to node at position 1 (value 1)
null ← [1] ↔ 2 ↔ 3 -> null, new_node=4
Why: We find the node after which we insert
Step 3: Set new_node's next to node 2 and prev to node 1
null ← 1 ↔ [4] ↔ 2 ↔ 3 -> null
Why: Link new node to neighbors
Step 4: Update node 1's next to new_node and node 2's prev to new_node
null ← 1 ↔ 4 ↔ 2 ↔ 3 -> null
Why: Complete the links so list stays connected
Result:
null ← 1 ↔ 4 ↔ 2 ↔ 3 -> null
Annotated Code
DSA Python
class Node:
    def __init__(self, data):
        self.data = data
        self.prev = None
        self.next = None

class DoublyLinkedList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        curr = self.head
        while curr.next:
            curr = curr.next
        curr.next = new_node
        new_node.prev = curr

    def insert_at_position(self, data, position):
        new_node = Node(data)  # create new node
        if position == 1:  # insert at head
            new_node.next = self.head
            if self.head:
                self.head.prev = new_node
            self.head = new_node
            return
        curr = self.head
        count = 1
        while curr and count < position - 1:
            curr = curr.next  # move to node before position
            count += 1
        if not curr:  # position is beyond list length
            return
        new_node.next = curr.next  # link new_node next
        if curr.next:
            curr.next.prev = new_node  # link next node prev
        curr.next = new_node  # link current node next
        new_node.prev = curr  # link new_node prev

    def __str__(self):
        values = []
        curr = self.head
        while curr:
            values.append(str(curr.data))
            curr = curr.next
        return ' ↔ '.join(values)

# Driver code
dll = DoublyLinkedList()
dll.append(1)
dll.append(2)
dll.append(3)
dll.insert_at_position(4, 2)
print(dll)
new_node = Node(data) # create new node
prepare new node to insert
if position == 1: # insert at head
handle insertion at start of list
while curr and count < position - 1: curr = curr.next # move to node before position count += 1
traverse to node before insertion point
new_node.next = curr.next # link new_node next
connect new node's next pointer
if curr.next: curr.next.prev = new_node # link next node prev
connect next node's prev pointer if exists
curr.next = new_node # link current node next
connect current node's next pointer
new_node.prev = curr # link new_node prev
connect new node's prev pointer
OutputSuccess
1 ↔ 4 ↔ 2 ↔ 3
Complexity Analysis
Time: O(n) because we may need to traverse up to n nodes to reach the insertion position
Space: O(1) because we only create one new node and use a few pointers
vs Alternative: Compared to inserting at head or tail which is O(1), inserting at a specific position requires traversal, making it O(n)
Edge Cases
Insert at position 1 (head insertion)
New node becomes the new head, previous head's prev updated
DSA Python
if position == 1:  # insert at head
Insert at position beyond list length
No insertion happens, list remains unchanged
DSA Python
if not curr:  # position is beyond list length
Insert into empty list at position 1
New node becomes the head
DSA Python
if position == 1:  # insert at head
When to Use This Pattern
When a problem asks to insert an element at a specific position in a doubly linked list, use traversal to find the spot and update four pointers to insert the node.
Common Mistakes
Mistake: Not updating the prev pointer of the node after the inserted node
Fix: Always update curr.next.prev = new_node if curr.next exists
Mistake: Not handling insertion at the head separately
Fix: Add a special case for position 1 to update head and pointers correctly
Summary
Inserts a new node at a given position in a doubly linked list by adjusting next and prev pointers.
Use when you need to add an element anywhere in the list, not just at the ends.
The key is to link the new node between its neighbors by updating four pointers carefully.