Bird
Raised Fist0
DSA C++programming

Insert at Specific Position in Doubly Linked List in DSA C++

Choose your learning style10 modes available
Mental Model
A doubly linked list lets you move forward and backward through nodes. To insert at a specific spot, you find that spot and adjust the nearby nodes to include the new one.
Analogy: Imagine a train with cars linked front and back. To add a new car in the middle, you disconnect the links between two cars and connect the new car in between, linking it to both neighbors.
null ← 1 ↔ 2 ↔ 3 ↔ 4 -> null
               ↑ (position 3)
Dry Run Walkthrough
Input: list: 1 ↔ 2 ↔ 4, insert value 3 at position 3
Goal: Insert the value 3 exactly between nodes 2 and 4
Step 1: start at head node 1, move to next node 2
null ← 1 ↔ [2↑] ↔ 4 -> null
Why: We move forward to reach the node before the insertion position
Step 2: create new node with value 3
new node 3 created (not linked yet)
Why: Prepare the new node to insert
Step 3: link new node 3 between nodes 2 and 4
null ← 1 ↔ 2 ↔ [3↑] ↔ 4 -> null
Why: Adjust pointers so 3 fits exactly between 2 and 4
Step 4: update node 2's next to 3 and node 4's prev to 3
null ← 1 ↔ 2 ↔ 3 ↔ 4 -> null
Why: Complete the double links to maintain list integrity
Result:
null ← 1 ↔ 2 ↔ 3 ↔ 4 -> null
Annotated Code
DSA C++
#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* prev;
    Node* next;
    Node(int val) : data(val), prev(nullptr), next(nullptr) {}
};

class DoublyLinkedList {
public:
    Node* head;
    DoublyLinkedList() : head(nullptr) {}

    void append(int val) {
        Node* newNode = new Node(val);
        if (!head) {
            head = newNode;
            return;
        }
        Node* temp = head;
        while (temp->next) {
            temp = temp->next;
        }
        temp->next = newNode;
        newNode->prev = temp;
    }

    void insertAtPosition(int val, int pos) {
        if (pos <= 0) return; // invalid position
        Node* newNode = new Node(val);
        if (pos == 1) {
            newNode->next = head;
            if (head) head->prev = newNode;
            head = newNode;
            return;
        }
        Node* temp = head;
        int currentPos = 1;
        while (temp && currentPos < pos - 1) {
            temp = temp->next;
            currentPos++;
        }
        if (!temp) return; // position out of bounds
        newNode->next = temp->next;
        if (temp->next) temp->next->prev = newNode;
        temp->next = newNode;
        newNode->prev = temp;
    }

    void printList() {
        Node* temp = head;
        while (temp) {
            cout << temp->data;
            if (temp->next) cout << " ↔ ";
            temp = temp->next;
        }
        cout << " -> null" << endl;
    }
};

int main() {
    DoublyLinkedList dll;
    dll.append(1);
    dll.append(2);
    dll.append(4);
    dll.insertAtPosition(3, 3);
    dll.printList();
    return 0;
}
while (temp && currentPos < pos - 1) { temp = temp->next; currentPos++; }
advance temp to node before insertion position
newNode->next = temp->next;
link new node's next to temp's next
if (temp->next) temp->next->prev = newNode;
link next node's prev to new node if it exists
temp->next = newNode;
link temp's next to new node
newNode->prev = temp;
link new node's prev to temp
OutputSuccess
1 ↔ 2 ↔ 3 ↔ 4 -> null
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
inserting at position 1 (head)
new node becomes the new head, previous head's prev updated
DSA C++
if (pos == 1) { newNode->next = head; if (head) head->prev = newNode; head = newNode; return; }
inserting at position beyond list length
no insertion happens, function returns early
DSA C++
if (!temp) return; // position out of bounds
inserting into empty list at position 1
new node becomes head
DSA C++
if (pos == 1) { newNode->next = head; if (head) head->prev = newNode; head = newNode; return; }
When to Use This Pattern
When a problem asks to insert a node at a specific position in a doubly linked list, use traversal to find the spot and adjust four pointers to insert cleanly.
Common Mistakes
Mistake: Not updating the prev pointer of the node after the inserted node
Fix: Always set newNode->next->prev = newNode if newNode->next exists
Mistake: Not handling insertion at head separately
Fix: Check if position is 1 and update head and pointers accordingly
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 carefully update four pointers to keep the list connected both forward and backward.

Practice

(1/5)
1. What happens when you insert a new node at position 1 in a doubly linked list?
easy
A. The list remains unchanged.
B. The new node becomes the new head of the list.
C. The new node replaces the last node.
D. The new node is added at the end of the list.

Solution

  1. Step 1: Understand position 1 in doubly linked list

    Position 1 means the start of the list, so the new node should be the first node.
  2. Step 2: Insert new node at head

    The new node's next pointer points to the old head, and the old head's previous pointer points back to the new node.
  3. Final Answer:

    The new node becomes the new head of the list. -> Option B
  4. Quick Check:

    Insert at position 1 = new head [OK]
Hint: Position 1 means insert at the start [OK]
Common Mistakes:
  • Inserting at position 1 but not updating head pointer
  • Not updating previous pointer of old head
  • Confusing position 1 with end of list
2. Which of the following is the correct syntax to insert a new node at position pos in a doubly linked list in C++?
easy
A. newNode->next = temp->next; temp->next->prev = newNode; temp->next = newNode; newNode->prev = temp;
B. newNode->prev = temp->prev; temp->prev->next = newNode; temp->prev = newNode; newNode->next = temp;
C. newNode->next = temp->prev; temp->prev->prev = newNode; temp->prev = newNode; newNode->prev = temp;
D. newNode->prev = temp->next; temp->next->next = newNode; temp->next = newNode; newNode->next = temp;

Solution

  1. Step 1: Identify correct pointer updates for insertion

    When inserting after temp, newNode's next points to temp's next, and newNode's prev points to temp.
  2. Step 2: Update surrounding nodes' pointers

    temp's next's prev must point to newNode, and temp's next must point to newNode.
  3. Final Answer:

    newNode->next = temp->next; temp->next->prev = newNode; temp->next = newNode; newNode->prev = temp; -> Option A
  4. Quick Check:

    Correct pointer updates = newNode->next = temp->next; temp->next->prev = newNode; temp->next = newNode; newNode->prev = temp; [OK]
Hint: Update next and prev pointers carefully [OK]
Common Mistakes:
  • Mixing up next and prev pointers
  • Not updating temp->next->prev pointer
  • Assigning pointers in wrong order causing broken links
3. Given the doubly linked list: 10 <-> 20 <-> 30 <-> null, what will be the list after inserting 15 at position 2?
void insertAtPosition(Node*& head, int data, int pos) {
  Node* newNode = new Node(data);
  if (pos == 1) {
    newNode->next = head;
    if (head) head->prev = newNode;
    head = newNode;
    return;
  }
  Node* temp = head;
  for (int i = 1; i < pos - 1 && temp != nullptr; i++) {
    temp = temp->next;
  }
  if (temp == nullptr) return;
  newNode->next = temp->next;
  if (temp->next) temp->next->prev = newNode;
  temp->next = newNode;
  newNode->prev = temp;
}
medium
A. 10 <-> 15 <-> 20 <-> 30 <-> null
B. 15 <-> 10 <-> 20 <-> 30 <-> null
C. 10 <-> 20 <-> 15 <-> 30 <-> null
D. 10 <-> 20 <-> 30 <-> 15 <-> null

Solution

  1. Step 1: Locate position 2 in the list

    Position 2 means after the first node (10). So temp points to node with data 10.
  2. Step 2: Insert new node with data 15 after temp

    New node's next points to 20, and prev points to 10. Update 10's next to new node and 20's prev to new node.
  3. Final Answer:

    10 <-> 15 <-> 20 <-> 30 <-> null -> Option A
  4. Quick Check:

    Insert at position 2 places new node after first node [OK]
Hint: Position 2 means insert after first node [OK]
Common Mistakes:
  • Inserting before first node instead of after
  • Not updating prev pointer of next node
  • Skipping position count in loop
4. Identify the error in the following code snippet for inserting at position pos in a doubly linked list:
void insertAtPosition(Node*& head, int data, int pos) {
  Node* newNode = new Node(data);
  if (pos == 1) {
    newNode->next = head;
    if (head) head->prev = newNode;
    head = newNode;
    return;
  }
  Node* temp = head;
  for (int i = 1; i < pos - 1; i++) {
    temp = temp->next;
  }
  newNode->next = temp->next;
  temp->next = newNode;
  newNode->prev = temp;
  if (newNode->next) newNode->next->prev = newNode;
}
medium
A. The newNode->next pointer is assigned after temp->next is changed.
B. The newNode->prev pointer is not set correctly.
C. The head pointer is not updated when inserting at position 1.
D. The loop does not check if temp is nullptr, causing possible crash.

Solution

  1. Step 1: Analyze the for loop traversal

    The loop moves temp forward but does not check if temp becomes nullptr, risking null pointer dereference.
  2. Step 2: Identify missing safety check

    Without checking temp != nullptr, accessing temp->next can cause a crash if pos is invalid or list is short.
  3. Final Answer:

    The loop does not check if temp is nullptr, causing possible crash. -> Option D
  4. Quick Check:

    Always check temp != nullptr in traversal loops [OK]
Hint: Always check for nullptr when traversing [OK]
Common Mistakes:
  • Ignoring nullptr checks in loops
  • Not updating head for position 1 insert
  • Incorrect order of pointer assignments
5. You have a doubly linked list: 5 <-> 10 <-> 15 <-> 20 <-> null. You want to insert a new node with value 12 at position 3. After insertion, what will be the correct sequence of the list? Also, explain how to handle insertion at the last position if the position is greater than the list length.
hard
A. 5 <-> 12 <-> 10 <-> 15 <-> 20 <-> null; Insert at last by replacing last node.
B. 5 <-> 10 <-> 15 <-> 12 <-> 20 <-> null; Insert at last by adding node before head.
C. 5 <-> 10 <-> 12 <-> 15 <-> 20 <-> null; Insert at last by traversing till last node and updating pointers.
D. 5 <-> 10 <-> 15 <-> 20 <-> 12 <-> null; Insert at last by ignoring position.

Solution

  1. Step 1: Insert 12 at position 3

    Position 3 means after second node (10). Insert new node between 10 and 15, updating next and prev pointers accordingly.
  2. Step 2: Handle insertion at last position if position > length

    Traverse to last node, then insert new node after it, updating last node's next and new node's prev pointers.
  3. Final Answer:

    5 <-> 10 <-> 12 <-> 15 <-> 20 <-> null; Insert at last by traversing till last node and updating pointers. -> Option C
  4. Quick Check:

    Insert at position 3 places node between 10 and 15; last insert by traversal [OK]
Hint: Insert at position or append if position too large [OK]
Common Mistakes:
  • Inserting at wrong position
  • Not updating prev pointer of next node
  • Ignoring last position insertion logic
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard