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 Doubly Linked List
Next article icon

Insert a Node after a given node in Doubly Linked List

Last Updated : 07 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = 2
Output: Linked List = 1 <-> 2 <-> 3 <-> 4
Explanation: New node 3 is inserted after key, that is node 2.

Input: Linked List = 1 <-> 2, newData = 4, key = 2
Output: Linked List = 1 <-> 2 <-> 4
Explanation: New node 4 is inserted after key, that is node 2.

Approach: To solve the problem, follow the below idea:

To insert a new node after a given node, we first find the given node in the doubly linked list. If the given node is not found, return the original linked list. Otherwise if the given node is found, say current node, we create a new node with new data and update its pointers: Update the previous pointer of new node to the current node and the next pointer of new node to the current node' s next. Then, update the next pointer of current node to the new node. Finally, if the new node is not the last node of the linked list, then we update the update previous pointer of new node’s next node to new node.

Insertion-after-a-given-node-in-Doubly-Linked-List
Insert node 3 after given node 2 in Doubly Linked List

To insert a new node after a specific node,

  • Find the given node in the doubly linked list, say curr.
  • Once we find it, create a new node with the new data, say new_node.
  • Update the new node’s previous pointer to given node and new node’s next pointer to the given node’s next, new_node->prev = curr and new_node->next = curr->next.
  • Then, we update the next pointer of given node with new node, curr->next = new_node.
  • Also, if the new node is not the last node of the linked list, then update previous pointer of new node’s next node to new node, new_node->next->prev = new_node.
C++
// C++ Program to insert a node after a given node of doubly linked list  #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 after a given node // in doubly linked list Node *insertAfter(Node *head, int key, int new_data) {      Node *curr = head;      // Iterate over Linked List to find the key     while (curr != nullptr) {         if (curr->data == key)             break;         curr = curr->next;     }      // if curr becomes null means, given key is not     // found in linked list     if (curr == nullptr)         return head;      // Create a new node     Node *new_node = new Node(new_data);      // Set prev of new node to given node     new_node->prev = curr;      // Set next of new node to next of given node     new_node->next = curr->next;      // Update next of given node to new node     curr->next = new_node;      // If the given node is not the last node of the linked list,    	// update the prev of new node's next with new node   	if(new_node->next != nullptr) {     	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 != nullptr) {         cout << " " << curr->data;         curr = curr->next;     }     cout << endl; }  int main() {      // Create a harcoded doubly linked list:     // 1 <-> 3 <-> 4     Node *head = new Node(1);     head->next = new Node(3);     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 a new node after node 1     cout << "Inserting Node with data 2 after node 1:";     int data = 2;     int key = 1;     head = insertAfter(head, key, data);      // Print the updated list     printList(head);      return 0; } 
C
// C Program to insert a node after a given node of doubly linked list  #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 after a given node in doubly linked list struct Node *insertAfter(struct Node *head, int key, int new_data) {     struct Node *curr = head;      // Iterate over Linked List to find the key     while (curr != NULL) {         if (curr->data == key)             break;         curr = curr->next;     }      // If curr becomes NULL, the given key     // is not found in linked list     if (curr == NULL)         return head;      // Create a new node     struct Node *new_node = createNode(new_data);      // Set prev of new node to the given node     new_node->prev = curr;      // Set next of new node to the next of given node     new_node->next = curr->next;      // Update next of given node to new node     curr->next = new_node;      // Update the prev of new node's next with new node     if (new_node->next != NULL)         new_node->next->prev = new_node;      return head; }  // Function to print the doubly 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 <-> 3 <-> 4     struct Node *head = createNode(1);     head->next = createNode(3);     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 a new node after node with key 1     printf("Inserting Node with data 2 after node 1 :");     int data = 2;     int key = 1;     head = insertAfter(head, key, data);      // Print the updated list     printList(head);      return 0; } 
Java
// Java Program to insert a node after a given node of doubly linked list  class Node {     int data;     Node next, prev;      Node(int newData) {         data = newData;         next = prev = null;     } }  public class GFG {      // Function to insert a new node after a given node in the doubly linked list     public static Node insertAfter(Node head, int key, int newData) {         Node curr = head;          // Iterate over Linked List to find the key         while (curr != null) {             if (curr.data == key)                 break;             curr = curr.next;         }          // If curr becomes null, the given key is not found in the linked list         if (curr == null)             return head;          // Create a new node         Node newNode = new Node(newData);          // Set prev of new node to the given node         newNode.prev = curr;          // Set next of new node to the next of the given node         newNode.next = curr.next;          // Update next of the given node to new node         curr.next = newNode;          // Update the prev of new node's next with the new node         if (newNode.next != null)             newNode.next.prev = newNode;          return head;     }      // Function to print the doubly 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 <-> 3 <-> 4         Node head = new Node(1);         head.next = new Node(3);         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 a new node after node with data 1         System.out.print("Inserting Node with data 2 after node 1 :");         int data = 2;         int key = 1;         head = insertAfter(head, key, data);          // Print the updated list         printList(head);     } } 
Python
# Python Program to insert a node after a given node of doubly linked list  class Node:     def __init__(self, new_data):         self.data = new_data         self.next = None         self.prev = None  def insert_after(head, key, new_data):     curr = head      # Iterate over Linked List to find the key     while curr is not None:         if curr.data == key:             break         curr = curr.next      # If curr becomes None, the given key is not found in the linked list     if curr is None:         return head      # Create a new node     new_node = Node(new_data)      # Set prev of new node to the given node     new_node.prev = curr      # Set next of new node to the next of the given node     new_node.next = curr.next      # Update next of the given node to new node     curr.next = new_node      # Update the prev of new node's next with the 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(f" {curr.data}", end='')         curr = curr.next     print()  if __name__ == "__main__":        # Create a hardcoded doubly linked list:     # 1 <-> 3 <-> 4     head = Node(1)     head.next = Node(3)     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 a new node after node with data 1     print("Inserting Node with data 2 after node 1 :", end='')     data = 2     key = 1     head = insert_after(head, key, data)      # Print the updated list     print_list(head) 
C#
// C# Program to insert a node after a given node of doubly linked list  using System;  class Node {     public int Data;     public Node Next;     public Node Prev;      public Node(int newData) {         Data = newData;         Next = null;         Prev = null;     } }  class GFG {     static Node InsertAfter(Node head, int key, int newData) {         Node curr = head;          // Iterate over Linked List to find the key         while (curr != null) {             if (curr.Data == key)                 break;             curr = curr.Next;         }          // If curr becomes null, the given key is not found in the linked list         if (curr == null)             return head;          // Create a new node         Node newNode = new Node(newData);          // Set prev of new node to the given node         newNode.Prev = curr;          // Set next of new node to next of the given node         newNode.Next = curr.Next;          // Update next of the given node to the new node         curr.Next = newNode;          // Update the prev of new node's next with the new node         if (newNode.Next != null)             newNode.Next.Prev = newNode;          return head;     }      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 <-> 3 <-> 4         Node head = new Node(1);         head.Next = new Node(3);         head.Next.Prev = head;         head.Next.Next = new Node(4);         head.Next.Next.Prev = head.Next;          // Print the original list         Console.Write("Original Linked List:");         PrintList(head);          // Insert a new node after node with data 1         Console.Write("Inserting Node with data 2 after node 1 :");         int data = 2;         int key = 1;         head = InsertAfter(head, key, data);          // Print the updated list         PrintList(head);     } } 
JavaScript
// Javascript Program to insert a node after a given node of doubly linked list  class Node {     constructor(data) {         this.data = data;         this.next = null;         this.prev = null;     } }  // Function to insert a new node after a given node in the doubly linked list function insertAfter(head, key, newData) {     let curr = head;      // Iterate over Linked List to find the key     while (curr !== null) {         if (curr.data === key) {             break;         }         curr = curr.next;     }      // If curr becomes null, the given key is not found in     // the linked list     if (curr === null) {         return head;     }      // Create a new node     const newNode = new Node(newData);      // Set prev of new node to the given node     newNode.prev = curr;      // Set next of new node to next of the given node     newNode.next = curr.next;      // Update next of the given node to the new node     curr.next = newNode;      // Update the prev of new node's next with the new node     if (newNode.next !== null) {         newNode.next.prev = newNode;     }      return head; }  function printList(head) {     let curr = head;     let result = "";     while (curr !== null) {         result += curr.data + " ";         curr = curr.next;     }     console.log(result); }  // Create a hardcoded doubly linked list: // 1 <-> 3 <-> 4  const head = new Node(1); head.next = new Node(3); 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 a new node after node with data 1 console.log("Inserting Node with data 2 after node 1:"); const data = 2; const key = 1; insertAfter(head, key, data);  // Print the updated list printList(head); 

Output
Original Linked List: 1 3 4 Inserting Node with data 2 after node 1: 1 2 3 4 

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


Next Article
Insert a Node at a specific position in Doubly Linked List

M

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

Similar Reads

  • 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
  • Insert a Node after a given Node in Linked List
    Given a linked list, the task is to insert a new node after a given node of the linked list. If the given node is not present in the linked list, print "Node not found". Examples: Input: LinkedList = 2 -> 3 -> 4 -> 5, newData = 1, key = 2Output: LinkedList = 2 -> 1 -> 3 -> 4 ->
    11 min read
  • Insert a node in Linked List before a given node
    Given a linked list, the task is to insert a new node with a specified value into a linked list before a node with a given key. Examples Input: head: 1 -> 2 -> 3 -> 4 -> 5 , newData = 6, key = 2Output: 1 -> 6 -> 2 -> 3 -> 4 -> 5 Explanation: After inserting node with value
    15+ 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 at a specific position in Doubly Linked List
    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 = 3Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node with data = 3 is inserted at po
    13 min read
  • Insert a Node at Front/Beginning of a Linked List
    Given a linked list, the task is to insert a new node at the beginning/start/front of the linked list. Example: Input: LinkedList = 2->3->4->5, NewNode = 1Output: 1 2 3 4 5 Input: LinkedList = 2->10, NewNode = 1Output: 1 2 10 Approach: To insert a new node at the front, we create a new n
    8 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
  • Insert Node at the End of a Linked List
    Given a linked list, the task is to insert a new node at the end of the linked list. Examples: Input: LinkedList = 2 -> 3 -> 4 -> 5, NewNode = 1Output: LinkedList = 2 -> 3 -> 4 -> 5 -> 1 Input: LinkedList = NULL, NewNode = 1Output: LinkedList = 1 Approach:  Inserting at the end
    9 min read
  • Insert value in sorted way in a sorted doubly linked list
    Given a Sorted Doubly Linked List in (non-decreasing order) and an element x, the task is to insert the element x into the correct position in the Sorted Doubly Linked List. Example: Input: LinkedList = 3<->5<->8<->10<->12 , x = 9Output: 3<->5<->8<->9<-
    10 min read
  • Convert given Binary Tree to Doubly Linked List in Linear time
    Given a Binary Tree (BT), the task is to convert it to a Doubly Linked List (DLL) in place. The left and right pointers in nodes will be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as the order of the given Binary Tree. The first node
    8 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