Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Insert a node at a specific position in a linked list
Next article icon

Insert a Node at a specific position in Doubly Linked List

Last Updated : 07 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a Doubly Linked List, the task is to insert a new node at a specific position in the linked list.

 Examples:

Input: Linked List = 1 <-> 2 <-> 4, newData = 3, position = 3
Output: Linked List = 1 <-> 2 <-> 3 <-> 4
Explanation: New node with data = 3 is inserted at position 3

Input: Linked List = 2 <-> 3, newData = 1, position = 1
Output: Linked List = 1 <-> 2 <-> 3
Explanation: New node with data = 1 is inserted at position 1

Approach:

The idea is to traverse the linked list to find the node at position - 1, say current node. If the position is valid, create a new node with the given data and update its pointers: Set the next pointer of new node to next of current node and previous pointer of new node to current node. Similarly, update next pointer of current node to the new node and prev pointer of new node’s next to the new node.

Insertion-at-a-Specific-Position-in-Doubly-Linked-List
Insert node 3 at position 3 in Doubly Linked List

To insert a new node at a specific position,

  • If position = 1, create a new node and make it the head of the linked list and return it.
  • Otherwise, traverse the list to reach the node at position – 1, say curr.
  • If the position is valid, create a new node with given data, say new_node.
  • Update the next pointer of new node to the next of current node and prev pointer of new node to current node, new_node->next = curr->next and new_node->prev = curr.
  • Similarly, update next pointer of current node to the new node, curr->next = new_node.
  • If the new node is not the last node, update prev pointer of new node’s next to the new node, new_node->next->prev = new_node.
C++
// C++ Program to insert a node at a given position  #include <bits/stdc++.h> using namespace std;  struct Node {     int data;     Node *next, *prev;      Node(int new_data) {         data = new_data;         next = prev = nullptr;     } };  // Function to insert a new node at a given position Node *insertAtPosition(Node *head, int pos, int new_data) {      // Create a new node     Node *new_node = new Node(new_data);      // Insertion at the beginning     if (pos == 1) {         new_node->next = head;          // If the linked list is not empty, set the prev of head to new node         if (head != NULL)             head->prev = new_node;          // Set the new node as the head of linked list         head = new_node;         return head;     }      Node *curr = head;     // Traverse the list to find the node before the     // insertion point     for (int i = 1; i < pos - 1 && curr != NULL; ++i) {         curr = curr->next;     }      // If the position is out of bounds     if (curr == NULL) {         cout << "Position is out of bounds." << endl;         delete new_node;         return head;     }      // Set the prev of new node to curr     new_node->prev = curr;      // Set the new of new node to next of curr     new_node->next = curr->next;      // Update the next of current node to new node     curr->next = new_node;      // If the new node is not the last node, update prev of next node to new node     if (new_node->next != NULL)         new_node->next->prev = new_node;      // Return the head of the doubly linked list     return head; }  void printList(Node *head) {     Node *curr = head;     while (curr != NULL) {         cout << curr->data << " ";         curr = curr->next;     }     cout << endl; }  int main() {      // Create a harcoded doubly linked list:     // 1 <-> 2 <-> 4     Node *head = new Node(1);     head->next = new Node(2);     head->next->prev = head;     head->next->next = new Node(4);     head->next->next->prev = head->next;      // Print the original list     cout << "Original Linked List: ";     printList(head);      // Insert new node with data 3 at position 3     cout << "Inserting Node with data 3 at position 3: ";     int data = 3;     int pos = 3;     head = insertAtPosition(head, pos, data);      // Print the updated list     printList(head);      return 0; } 
C
// C Program to insert a node at a given position  #include <stdio.h>  struct Node {     int data;     struct Node *next;     struct Node *prev; };  // Function to create a new node with the given data struct Node *createNode(int new_data) {     struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));     new_node->data = new_data;     new_node->next = NULL;     return new_node; }  // Function to insert a new node at a given position struct Node* insertAtPosition(struct Node *head, int pos, int new_data) {     // Create a new node     struct Node *new_node = createNode(new_data);      // Insertion at the beginning     if (pos == 1) {         new_node->next = head;          // If the linked list is not empty, set the prev of head to new node         if (head != NULL) {             head->prev = new_node;         }          // Set the new node as the head of linked list         head = new_node;         return head;     }      struct Node *curr = head;        // Traverse the list to find the node before the insertion point     for (int i = 1; i < pos - 1 && curr != NULL; ++i) {         curr = curr->next;     }      // If the position is out of bounds     if (curr == NULL) {         printf("Position is out of bounds.\n");         free(new_node);         return head;     }      // Set the prev of new node to curr     new_node->prev = curr;      // Set the next of new node to next of curr     new_node->next = curr->next;      // Update the next of current node to new node     curr->next = new_node;      // If the new node is not the last node, update the prev of next node to new node     if (new_node->next != NULL) {         new_node->next->prev = new_node;     }      // Return the head of the doubly linked list     return head; }  // Function to print the linked list void printList(struct Node *head) {     struct Node *curr = head;     while (curr != NULL) {         printf("%d ", curr->data);         curr = curr->next;     }     printf("\n"); }  int main() {        // Create a hardcoded doubly linked list:     // 1 <-> 2 <-> 4     struct Node *head = createNode(1);     head->next = createNode(2);     head->next->prev = head;     head->next->next = createNode(4);     head->next->next->prev = head->next;      // Print the original list     printf("Original Linked List: ");     printList(head);      // Insert new node with data 3 at position 3     printf("Inserting Node with data 3 at position 3: ");     int data = 3;     int pos = 3;     head = insertAtPosition(head, pos, data);      // Print the updated list     printList(head);      return 0; } 
Java
// Java Program to insert a node at a given position  class Node {     int data;     Node next;     Node prev;      Node(int new_data) {         data = new_data;         next = prev = null;     } }  public class GFG {      // Function to insert a new node at a given position     public static Node insertAtPosition(Node head, int pos, int new_data) {         // Create a new node         Node new_node = new Node(new_data);          // Insertion at the beginning         if (pos == 1) {             new_node.next = head;              // If the linked list is not empty, set the prev of head to new node             if (head != null) {                 head.prev = new_node;             }              // Set the new node as the head of linked list             head = new_node;             return head;         }          Node curr = head;                // Traverse the list to find the node before the insertion point         for (int i = 1; i < pos - 1 && curr != null; ++i) {             curr = curr.next;         }          // If the position is out of bounds         if (curr == null) {             System.out.println("Position is out of bounds.");             return head;         }          // Set the prev of new node to curr         new_node.prev = curr;          // Set the next of new node to next of curr         new_node.next = curr.next;          // Update the next of current node to new node         curr.next = new_node;          // If the new node is not the last node, update prev of next node to new node         if (new_node.next != null) {             new_node.next.prev = new_node;         }          // Return the head of the doubly linked list         return head;     }      // Function to print the linked list     public static void printList(Node head) {         Node curr = head;         while (curr != null) {             System.out.print(curr.data + " ");             curr = curr.next;         }         System.out.println();     }      public static void main(String[] args) {                // Create a hardcoded doubly linked list:         // 1 <-> 2 <-> 4         Node head = new Node(1);         head.next = new Node(2);         head.next.prev = head;         head.next.next = new Node(4);         head.next.next.prev = head.next;          // Print the original list         System.out.print("Original Linked List: ");         printList(head);          // Insert new node with data 3 at position 3         System.out.print("Inserting Node with data 3 at position 3: ");         int data = 3;         int pos = 3;         head = insertAtPosition(head, pos, data);          // Print the updated list         printList(head);     } } 
Python
# Python Program to insert a node at a given position  class Node:     def __init__(self, new_data):         self.data = new_data         self.next = None         self.prev = None  def insert_at_position(head, pos, new_data):        # Create a new node     new_node = Node(new_data)      # Insertion at the beginning     if pos == 1:         new_node.next = head          # If the linked list is not empty, set the prev of head to new node         if head is not None:             head.prev = new_node          # Set the new node as the head of the linked list         head = new_node         return head      curr = head          # Traverse the list to find the node before the insertion point     for _ in range(1, pos - 1):         if curr is None:             print("Position is out of bounds.")             return head         curr = curr.next      # If the position is out of bounds     if curr is None:         print("Position is out of bounds.")         return head      # Set the prev of new node to curr     new_node.prev = curr      # Set the next of new node to next of curr     new_node.next = curr.next      # Update the next of current node to new node     curr.next = new_node      # If the new node is not the last node, update prev of next node to new node     if new_node.next is not None:         new_node.next.prev = new_node      return head  def print_list(head):     curr = head     while curr is not None:         print(curr.data, end=" ")         curr = curr.next     print()  if __name__ == "__main__":        # Create a hardcoded doubly linked list:     # 1 <-> 2 <-> 4     head = Node(1)     head.next = Node(2)     head.next.prev = head     head.next.next = Node(4)     head.next.next.prev = head.next      # Print the original list     print("Original Linked List: ", end="")     print_list(head)      # Insert new node with data 3 at position 3     print("Inserting Node with data 3 at position 3: ", end="")     data = 3     pos = 3     head = insert_at_position(head, pos, data)      # Print the updated list     print_list(head) 
C#
// C# Program to insert a node at a given position  using System;  class Node {     public int Data;     public Node Next;     public Node Prev;      public Node(int data) {         Data = data;         Next = null;         Prev = null;     } }  class GFG {        // Function to insert a new node at a given position     static Node InsertAtPosition(Node head, int pos, int newData) {                // Create a new node         Node newNode = new Node(newData);          // Insertion at the beginning         if (pos == 1) {             newNode.Next = head;             if (head != null)                 head.Prev = newNode;             head = newNode;             return head;         }          Node curr = head;                	// Traverse the list to find the node before the insertion point         for (int i = 1; i < pos - 1 && curr != null; ++i) {             curr = curr.Next;         }          // If the position is out of bounds         if (curr == null) {             Console.WriteLine("Position is out of bounds.");             return head;         }          // Set the prev of new node to curr         newNode.Prev = curr;          // Set the next of new node to the next of curr         newNode.Next = curr.Next;          // Update the next of current node to new node         curr.Next = newNode;          // If the new node is not the last node, update prev of next node to new node         if (newNode.Next != null)             newNode.Next.Prev = newNode;          return head;     }      // Function to print the list     static void PrintList(Node head) {         Node curr = head;         while (curr != null) {             Console.Write(curr.Data + " ");             curr = curr.Next;         }         Console.WriteLine();     }      static void Main() {                // Create a hardcoded doubly linked list:         // 1 <-> 2 <-> 4         Node head = new Node(1);         head.Next = new Node(2);         head.Next.Prev = head;         head.Next.Next = new Node(4);         head.Next.Next.Prev = head.Next;          // Print the original list         Console.WriteLine("Original Linked List: ");         PrintList(head);          // Insert new node with data 3 at position 3         Console.WriteLine("Inserting Node with data 3 at position 3: ");         head = InsertAtPosition(head, 3, 3);          // Print the updated list         PrintList(head);     } } 
JavaScript
// Javascript Program to insert a node at a given position  class Node {     constructor(data) {         this.data = data;         this.next = null;         this.prev = null;     } }  // Function to insert a new node at a given position function insertAtPosition(head, pos, newData) {      // Create a new node     let newNode = new Node(newData);      // Insertion at the beginning     if (pos === 1) {         newNode.next = head;         if (head !== null) {             head.prev = newNode;         }         head = newNode;         return head;     }      let curr = head;          // Traverse the list to find the node before the insertion point     for (let i = 1; i < pos - 1 && curr !== null; ++i) {         curr = curr.next;     }      // If the position is out of bounds     if (curr === null) {         console.log("Position is out of bounds.");         return head;     }      // Set the prev of new node to curr     newNode.prev = curr;      // Set the next of new node to the next of curr     newNode.next = curr.next;      // Update the next of current node to new node     curr.next = newNode;      // If the new node is not the last node, update prev of next node to new node     if (newNode.next !== null) {         newNode.next.prev = newNode;     }      return head; }  // Function to print the list function printList(head) {     let curr = head;     while (curr !== null) {         console.log(curr.data + " ");         curr = curr.next;     }     console.log(); }  // Create a hardcoded doubly linked list: // 1 <-> 2 <-> 4 let head = new Node(1); head.next = new Node(2); head.next.prev = head; head.next.next = new Node(4); head.next.next.prev = head.next;  // Print the original list console.log("Original Linked List:"); printList(head);  // Insert new node with data 3 at position 3 console.log("Inserting Node with data 3 at position 3:"); head = insertAtPosition(head, 3, 3);  // Print the updated list printList(head); 

Output
Original Linked List: 1 2 4  Inserting Node with data 3 at position 3: 1 2 3 4  

Time Complexity: O(N), where N is the number of nodes in doubly linked list
Auxiliary Space: O(1)


Next Article
Insert a node at a specific position in a linked list

M

mrityuanjay8vae
Improve
Article Tags :
  • Linked List
  • DSA
  • doubly linked list
Practice Tags :
  • Linked List

Similar Reads

  • Insert a node at a specific position in a linked list
    Given a singly linked list, a position pos, and data, the task is to insert that data into a linked list at the given position. Examples: Input: 3->5->8->10, data = 2, pos = 2Output: 3->2->5->8->10 Input: 3->5->8->10, data = 11, pos = 5Output: 3->5->8->10->1
    8 min read
  • Insertion at Specific Position in a Circular Doubly Linked List
    Prerequisite: Insert Element Circular Doubly Linked List.Convert an Array to a Circular Doubly Linked List.Given the start pointer pointing to the start of a Circular Doubly Linked List, an element and a position. The task is to insert the element at the specified position in the given Circular Doub
    15+ min read
  • XOR Linked List - Insert an element at a specific position
    Given a XOR linked list and two integers position and value, the task is to insert a node containing value as the positionth node of the XOR Linked List. Examples: Input: 4<-->7<-->9<-->7, position = 3, value = 6 Output: 4<-->7<-->6<-->9<-->7Explanation: Ins
    15+ min read
  • Insertion at specific position in circular linked list
    Inserting an element at a specific position in a circular linked list is a common operation that involves adjusting pointers in a circular structure. Unlike a regular linked list, where the last node points to NULL, a circular linked list’s last node points back to the head, forming a loop. This pro
    10 min read
  • Insert a Node at the end of Doubly Linked List
    Given a Doubly Linked List, the task is to insert a new node at the end of the linked list. Examples: Input: Linked List = 1 <-> 2 <-> 3, NewNode = 4Output: Linked List = 1 <-> 2 <-> 3 <-> 4 Input: Linked List = NULL, NewNode = 1Output: Linked List = 1 Approach: Inserti
    9 min read
  • Insert a Node after a given node in Doubly Linked List
    Given a Doubly Linked List, the task is to insert a new node after a given node in the linked list. Examples: Input: Linked List = 1 <-> 2 <-> 4, newData = 3, key = 2Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node 3 is inserted after key, that is node 2.
    11 min read
  • Delete a Doubly Linked List node at a given position
    Given a doubly linked list and a position pos, the task is to delete the node at the given position from the beginning of Doubly Linked List. Input: LinkedList: 1<->2<->3, pos = 2Output: LinkedList: 1<->3 Input: LinkedList: 1<->2<->3, pos = 1Output: LinkedList: 2<-
    9 min read
  • Delete a Linked List node at a given position
    Given a singly linked list and a position (1-based indexing), the task is to delete a linked list node at the given position. Note: Position will be valid (i.e, 1 <= position <= linked list length) Example: Input: position = 2, Linked List = 8->2->3->1->7Output: Linked List = 8-
    8 min read
  • Insert a Node before a given node in Doubly Linked List
    Given a Doubly Linked List, the task is to insert a new node before a given node in the linked list. Examples: Input: Linked List = 1 <-> 3 <-> 4, newData = 2, key = 3Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node with data 2 is inserted before the node
    12 min read
  • How to insert a Node in a Singly Linked List at a given Position using Recursion
    Given a singly linked list as list, a position, and a node, the task is to insert that element in the given linked list at a given position using recursion. Examples: Input: list = 1->2->3->4->5->6->7, node = (val=100,next=null), position = 4 Output: 1->2->3->100->4-
    14 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences