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:
Deletion at different positions in a Circular Linked List
Next article icon

Insertion at Specific Position in a Circular Doubly Linked List

Last Updated : 02 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Doubly Linked List. 

Image

The idea is to count the total number of elements in the list. Check whether the specified location is valid or not, i.e. location is within the count.

If location is valid:  

  1. Create a newNode in the memory.
  2. Traverse in the list using a temporary pointer(temp) till the node just before the given position at which a new node is needed to be inserted.
  3. Insert the new node by performing below operations: 
    • Assign newNode->next = temp->next
    • Assign newNode->prev as temp->next
    • Assign temp->next as newNode
    • Assign (temp->next)->prev as newNode->next

Below is the implementation of the above idea:  

C++
// CPP program to convert insert an element at a specific // position in a circular doubly linked list  #include <bits/stdc++.h> using namespace std;  // Doubly linked list node struct node {     int data;     struct node* next;     struct node* prev; };  // Utility function to create a node in memory struct node* getNode() {     return ((struct node*)malloc(sizeof(struct node))); }  // Function to display the list int displayList(struct node* temp) {     struct node* t = temp;     if (temp == NULL)         return 0;     else {         cout << "The list is: ";          while (temp->next != t) {             cout << temp->data << " ";             temp = temp->next;         }          cout << temp->data << endl;          return 1;     } }  // Function to count number of // elements in the list int countList(struct node* start) {     // Declare temp pointer to     // traverse the list     struct node* temp = start;      // Variable to store the count     int count = 0;      // Iterate the list and increment the count     while (temp->next != start) {         temp = temp->next;         count++;     }      // As the list is circular, increment the     // counter at last     count++;      return count; }  // Function to insert a node at a given position // in the circular doubly linked list bool insertAtLocation(struct node* start, int data, int loc) {     // Declare two pointers     struct node *temp, *newNode;     int i, count;      // Create a new node in memory     newNode = getNode();      // Point temp to start     temp = start;      // count of total elements in the list     count = countList(start);      // If list is empty or the position is     // not valid, return false     if (temp == NULL || count < loc)         return false;      else {         // Assign the data         newNode->data = data;          // Iterate till the loc         for (i = 1; i < loc - 1; i++) {             temp = temp->next;         }          // See in Image, circle 1         newNode->next = temp->next;          // See in Image, Circle 2         (temp->next)->prev = newNode;          // See in Image, Circle 3         temp->next = newNode;          // See in Image, Circle 4         newNode->prev = temp;          return true;     }      return false; }  // Function to create circular doubly linked list // from array elements void createList(int arr[], int n, struct node** start) {     // Declare newNode and temporary pointer     struct node *newNode, *temp;     int i;      // Iterate the loop until array length     for (i = 0; i < n; i++) {         // Create new node         newNode = getNode();          // Assign the array data         newNode->data = arr[i];          // If it is first element         // Put that node prev and next as start         // as it is circular         if (i == 0) {             *start = newNode;             newNode->prev = *start;             newNode->next = *start;         }          else {             // Find the last node             temp = (*start)->prev;              // Add the last node to make them             // in circular fashion             temp->next = newNode;             newNode->next = *start;             newNode->prev = temp;             temp = *start;             temp->prev = newNode;         }     } }  // Driver Code int main() {     // Array elements to create     // circular doubly linked list     int arr[] = { 1, 2, 3, 4, 5, 6 };     int n = sizeof(arr) / sizeof(arr[0]);      // Start Pointer     struct node* start = NULL;      // Create the List     createList(arr, n, &start);      // Display the list before insertion     displayList(start);      // Inserting 8 at 3rd position     insertAtLocation(start, 8, 3);      // Display the list after insertion     displayList(start);      return 0; } 
Java
// Doubly linked list node  class node  {      int data;      node next;      node prev;               node(int value){       data=value;       next=null;       prev=null;     } };  // Java program to convert insert // an element at a specific position // in a circular doubly linked listing,  // end and middle  class GFG { static node head=null; // Function to display the list  static int displayList()  {      node temp = head;      if (temp == null)          return 0;      else      {          System.out.println( "The list is: ");           while (temp.next != head)          {              System.out.print( temp.data + " ");              temp = temp.next;          }           System.out.println( temp.data );           return 1;      }  }   // Function to count number of  // elements in the list  static int countList()  {      // Declare temp pointer to      // traverse the list      node temp = head;       // Variable to store the count      int count = 0;       // Iterate the list and      // increment the count      while (temp.next != head)      {          temp = temp.next;          count++;      }       // As the list is circular, increment       // the counter at last      count++;       return count;  }   // Function to insert a node at  // a given position in the // circular doubly linked list  static void insertAtLocation(int data, int loc)  {      // Declare two pointers      node temp=head;      int i, count;       // count of total elements in the list      count = countList();       // If list is empty or the position is      // not valid, return false      if (temp == null || count < loc)          return;      else     {          // Create a new node in memory          node newNode = new node(data);                 // Iterate till the loc          for (i = 1; i < loc - 1; i++)          {              temp = temp.next;          }           // See in Image, circle 1          newNode.next = temp.next;           // See in Image, Circle 2          temp.next.prev = newNode;           // See in Image, Circle 3          temp.next = newNode;           // See in Image, Circle 4          newNode.prev = temp;      }   }   // Function to create circular doubly   // linked list from array elements  static void createList(int arr[], int n)  {      // Declare newNode and temporary pointer      node temp=head;      int i;       // Iterate the loop until array length      for (i = 0; i < n; i++)      {          // Create new node         node newNode =new node(arr[i]);           // If it is first element          if (i == 0)          {              head = newNode;                temp=newNode;         }           else          {               // Add the last node to make them              // in circular fashion              temp.next = newNode;              newNode.next = head;              newNode.prev = temp;              temp = newNode;          }      } }   // Driver Code  public static void main(String args[]) {      // Array elements to create      // circular doubly linked list      int arr[] = { 1, 2, 3, 4, 5, 6 };      int n = arr.length;       // Create the List      createList(arr, n);       // Display the list before insertion      displayList();       // Inserting 8 at 3rd position      insertAtLocation(8, 3);       // Display the list after insertion      displayList();  }  }  // This code is contributed by shubhamrajput6156 
Python
# Python3 program to insert an element  # at a specific position in a  # circular doubly linked list  # Node of the doubly linked list  class Node:           def __init__(self, data):          self.data = data          self.prev = None         self.next = None  # Utility function to create # a node in memory def getNode():      return (Node(0))  # Function to display the list def displayList(temp):      t = temp     if (temp == None):         return 0     else :         print("The list is: ", end = " ")          while (temp.next != t):              print( temp.data, end = " ")             temp = temp.next                  print(temp.data )          return 1  # Function to count number of # elements in the list def countList( start):      # Declare temp pointer to     # traverse the list     temp = start      # Variable to store the count     count = 0      # Iterate the list and increment the count     while (temp.next != start) :         temp = temp.next         count = count + 1      # As the list is circular, increment the     # counter at last     count = count + 1      return count  # Function to insert a node at a given position # in the circular doubly linked list def insertAtLocation(start, data, loc):      # Declare two pointers     temp = None     newNode = None     i = 0     count = 0      # Create a new node in memory     newNode = getNode()      # Point temp to start     temp = start      # count of total elements in the list     count = countList(start)      # If list is empty or the position is     # not valid, return False     if (temp == None or count < loc):         return start      else :                  # Assign the data         newNode.data = data          # Iterate till the loc         i = 1;         while(i < loc - 1) :             temp = temp.next             i = i + 1          # See in Image, circle 1         newNode.next = temp.next          # See in Image, Circle 2         (temp.next).prev = newNode          # See in Image, Circle 3         temp.next = newNode          # See in Image, Circle 4         newNode.prev = temp          return start          return start  # Function to create circular  # doubly linked list from array elements def createList(arr, n, start):      # Declare newNode and temporary pointer     newNode = None     temp = None     i = 0      # Iterate the loop until array length     while (i < n) :                  # Create new node         newNode = getNode()          # Assign the array data         newNode.data = arr[i]          # If it is first element         # Put that node prev and next as start         # as it is circular         if (i == 0) :             start = newNode             newNode.prev = start             newNode.next = start                  else :                          # Find the last node             temp = (start).prev              # Add the last node to make them             # in circular fashion             temp.next = newNode             newNode.next = start             newNode.prev = temp             temp = start             temp.prev = newNode         i = i + 1;          return start  # Driver Code if __name__ == "__main__":       # Array elements to create     # circular doubly linked list     arr = [ 1, 2, 3, 4, 5, 6]      n = len(arr)      # Start Pointer     start = None      # Create the List     start = createList(arr, n, start)      # Display the list before insertion     displayList(start)      # Inserting 8 at 3rd position     start = insertAtLocation(start, 8, 3)      # Display the list after insertion     displayList(start)      # This code is contributed by Arnab Kundu 
C#
// C# program to convert insert  // an element at a specific position  // in a circular doubly linked listing,  // end and middle  using System;  class GFG  {   // Doubly linked list node  public class node  {      public int data;      public node next;      public node prev;  };   // Utility function to create a node in memory  static node getNode()  {      return new node();  }   // Function to display the list  static int displayList( node temp)  {      node t = temp;      if (temp == null)          return 0;      else     {          Console.WriteLine( "The list is: ");           while (temp.next != t)          {              Console.Write( temp.data + " ");              temp = temp.next;          }           Console.WriteLine( temp.data );           return 1;      }  }   // Function to count number of  // elements in the list  static int countList( node start)  {      // Declare temp pointer to      // traverse the list      node temp = start;       // Variable to store the count      int count = 0;       // Iterate the list and      // increment the count      while (temp.next != start)      {          temp = temp.next;          count++;      }       // As the list is circular, increment      // the counter at last      count++;       return count;  }   // Function to insert a node at  // a given position in the  // circular doubly linked list  static node insertAtLocation( node start,                          int data, int loc)  {      // Declare two pointers      node temp, newNode;      int i, count;       // Create a new node in memory      newNode = getNode();       // Point temp to start      temp = start;       // count of total elements in the list      count = countList(start);       // If list is empty or the position is      // not valid, return false      if (temp == null || count < loc)          return start;       else     {          // Assign the data          newNode.data = data;           // Iterate till the loc          for (i = 1; i < loc - 1; i++)          {              temp = temp.next;          }           // See in Image, circle 1          newNode.next = temp.next;           // See in Image, Circle 2          (temp.next).prev = newNode;           // See in Image, Circle 3          temp.next = newNode;           // See in Image, Circle 4          newNode.prev = temp;           return start;      }   }   // Function to create circular doubly  // linked list from array elements  static node createList(int []arr, int n, node start)  {      // Declare newNode and temporary pointer      node newNode, temp;      int i;       // Iterate the loop until array length      for (i = 0; i < n; i++)      {          // Create new node          newNode = getNode();           // Assign the array data          newNode.data = arr[i];           // If it is first element          // Put that node prev and next as start          // as it is circular          if (i == 0)          {              start = newNode;              newNode.prev = start;              newNode.next = start;          }           else         {              // Find the last node              temp = (start).prev;               // Add the last node to make them              // in circular fashion              temp.next = newNode;              newNode.next = start;              newNode.prev = temp;              temp = start;              temp.prev = newNode;          }      }      return start;  }   // Driver Code  public static void Main()  {      // Array elements to create      // circular doubly linked list      int []arr = { 1, 2, 3, 4, 5, 6 };      int n = arr.Length;       // Start Pointer      node start = null;       // Create the List      start = createList(arr, n, start);       // Display the list before insertion      displayList(start);       // Inserting 8 at 3rd position      start = insertAtLocation(start, 8, 3);       // Display the list after insertion      displayList(start);  }  }   /* This code contributed by PrinciRaj1992 */ 
JavaScript
<script>       // JavaScript program to convert insert       // an element at a specific position       // in a circular doubly linked listing,       // end and middle       // Doubly linked list node       class node {         constructor() {           this.data = 0;           this.next = null;           this.prev = null;         }       }        // Utility function to create a node in memory       function getNode() {         return new node();       }        // Function to display the list       function displayList(temp) {         var t = temp;         if (temp == null) return 0;         else {           document.write("The list is: ");            while (temp.next != t) {             document.write(temp.data + " ");             temp = temp.next;           }            document.write(temp.data + "<br>");            return 1;         }       }        // Function to count number of       // elements in the list       function countList(start)       {                // Declare temp pointer to         // traverse the list         var temp = start;          // Variable to store the count         var count = 0;          // Iterate the list and         // increment the count         while (temp.next != start) {           temp = temp.next;           count++;         }          // As the list is circular, increment         // the counter at last         count++;          return count;       }        // Function to insert a node at       // a given position in the       // circular doubly linked list       function insertAtLocation(start, data, loc) {         // Declare two pointers         var temp, newNode;         var i, count;          // Create a new node in memory         newNode = getNode();          // Point temp to start         temp = start;          // count of total elements in the list         count = countList(start);          // If list is empty or the position is         // not valid, return false         if (temp == null || count < loc) return start;         else {           // Assign the data           newNode.data = data;            // Iterate till the loc           for (i = 1; i < loc - 1; i++) {             temp = temp.next;           }            // See in Image, circle 1           newNode.next = temp.next;            // See in Image, Circle 2           temp.next.prev = newNode;            // See in Image, Circle 3           temp.next = newNode;            // See in Image, Circle 4           newNode.prev = temp;            return start;         }       }        // Function to create circular doubly       // linked list from array elements       function createList(arr, n, start)        {                // Declare newNode and temporary pointer         var newNode, temp;         var i;          // Iterate the loop until array length         for (i = 0; i < n; i++)         {                    // Create new node           newNode = getNode();            // Assign the array data           newNode.data = arr[i];            // If it is first element           // Put that node prev and next as start           // as it is circular           if (i == 0)            {             start = newNode;             newNode.prev = start;             newNode.next = start;           }           else            {                        // Find the last node             temp = start.prev;              // Add the last node to make them             // in circular fashion             temp.next = newNode;             newNode.next = start;             newNode.prev = temp;             temp = start;             temp.prev = newNode;           }         }         return start;       }        // Driver Code       // Array elements to create       // circular doubly linked list       var arr = [1, 2, 3, 4, 5, 6];       var n = arr.length;        // Start Pointer       var start = null;        // Create the List       start = createList(arr, n, start);        // Display the list before insertion       displayList(start);        // Inserting 8 at 3rd position       start = insertAtLocation(start, 8, 3);        // Display the list after insertion       displayList(start);              // This code is contributed by rdtank.     </script> 

Output
The list is: 1 2 3 4 5 6 The list is: 1 2 8 3 4 5 6

complexities Analysis:

  • Time Complexity:O(n) => for counting the list as we are using a loop to traverse linearly, O(n) => Inserting the elements, as we are using a loop to traverse linearly. So, total complexity is O(n + n) = O(n). Where n is the number of nodes in the linked list.
  • Auxiliary Space: O(1), as we are not using any extra space. 

New Approach:- Here’s an alternative approach to inserting an element at a specific position in a circular doubly linked list.

Algorithm :

1. Define the structure for a doubly linked list node (`Node`) with data, `next` pointer, and `prev` pointer.

2. Create a function `getNode` that allocates memory for a new node, initializes its data and pointers, and returns the new node.

3. Create a function `displayList` to print the elements of the circular doubly linked list. It traverses the list starting from the `start` node and prints the data of each node until it reaches the `start` node again.

4. Create a function `countList` to count the number of elements in the circular doubly linked list. It starts from the `start` node and increments a counter while traversing the list until it reaches the `start` node again. The final count is returned.

5. Create a function `insertAtLocation` to insert a new node at a given position in the circular doubly linked list. It takes the address of the `start` pointer, the data to be inserted, and the desired position as input.

6. First, count the number of elements in the list using the `countList` function. If the specified position is less than 1 or greater than the count plus one, return false to indicate an invalid position.

7. Create a new node using `getNode` function and assign the input data to it.

8. If the list is empty (start pointer is NULL), make the new node the start node by pointing its `next` and `prev` pointers to itself.

9. If the desired position is 1, insert the new node at the beginning of the list. Update the pointers of the new node, the previous start node, and the last node in the list to maintain the circular doubly linked structure.

10. If the desired position is other than 1, traverse the list until the node just before the desired position. Update the pointers of the new node, the current node, and the next node to insert the new node at the desired position.

11. Finally, return true to indicate successful insertion.

12. In the `main` function, create the circular doubly linked list by inserting elements from the given array using the `insertAtLocation` function.

13. Display the list before insertion.

14. Insert a new node with data 8 at the 3rd position using the `insertAtLocation` function.

15. Display the list after insertion.

16. The program ends.

Below is the implementation of the above idea:  

C++
#include <bits/stdc++.h> using namespace std;  // Doubly linked list node struct Node {     int data;     struct Node* next;     struct Node* prev; };  // Function to create a new node struct Node* getNode(int data) {     struct Node* newNode = new Node;     newNode->data = data;     newNode->prev = NULL;     newNode->next = NULL;     return newNode; }  // Function to display the list void displayList(struct Node* start) {     if (start == NULL) {         cout << "The list is empty." << endl;         return;     }      cout << "The list is: ";     struct Node* temp = start;      do {         cout << temp->data << " ";         temp = temp->next;     } while (temp != start);      cout << endl; }  // Function to count the number of elements in the list int countList(struct Node* start) {     if (start == NULL)         return 0;      int count = 0;     struct Node* temp = start;      do {         count++;         temp = temp->next;     } while (temp != start);      return count; }  // Function to insert a node at a given position bool insertAtLocation(struct Node** start, int data, int loc) {     int count = countList(*start);      if (loc < 1 || loc > count + 1)         return false;      struct Node* newNode = getNode(data);      // If the list is empty     if (*start == NULL) {         *start = newNode;         newNode->next = newNode;         newNode->prev = newNode;     }     // If the node is to be inserted at the beginning     else if (loc == 1) {         newNode->next = *start;         newNode->prev = (*start)->prev;         (*start)->prev->next = newNode;         (*start)->prev = newNode;         *start = newNode;     }     else {         struct Node* temp = *start;         int currPos = 1;          // Traverse to the node before the desired position         while (currPos < loc - 1) {             temp = temp->next;             currPos++;         }          // Insert the new node         newNode->next = temp->next;         newNode->prev = temp;         temp->next->prev = newNode;         temp->next = newNode;     }      return true; }  // Driver Code int main() {     // Array elements to create     // circular doubly linked list     int arr[] = { 1, 2, 3, 4, 5, 6 };     int n = sizeof(arr) / sizeof(arr[0]);      // Start Pointer     struct Node* start = NULL;      // Create the List     for (int i = 0; i < n; i++)         insertAtLocation(&start, arr[i], i + 1);      // Display the list before insertion     displayList(start);      // Inserting 8 at 3rd position     insertAtLocation(&start, 8, 3);      // Display the list after insertion     displayList(start);      return 0; } 
Java
// Java code implementation  import java.io.*;  // creating the node     class Node {     int data;     Node next;     Node prev;          public Node(int data) {         this.data = data;         this.next = null;         this.prev = null;     } }  public class CircularDoublyLinkedList {          // Function to display the list     static void displayList(Node start) {         if (start == null) {             System.out.println("The list is empty.");             return;         }          System.out.print("The list is: ");         Node temp = start;          do {             System.out.print(temp.data + " ");             temp = temp.next;         } while (temp != start);          System.out.println();     }      // Function to count the number of elements in the list     static int countList(Node start) {         if (start == null)             return 0;          int count = 0;         Node temp = start;          do {             count++;             temp = temp.next;         } while (temp != start);          return count;     }      // Function to insert a node at a given position     static boolean insertAtLocation(Node[] start, int data, int loc) {         int count = countList(start[0]);          if (loc < 1 || loc > count + 1)             return false;          Node newNode = new Node(data);          // If the list is empty         if (start[0] == null) {             start[0] = newNode;             newNode.next = newNode;             newNode.prev = newNode;         }         // If the node is to be inserted at the beginning         else if (loc == 1) {             newNode.next = start[0];             newNode.prev = start[0].prev;             start[0].prev.next = newNode;             start[0].prev = newNode;             start[0] = newNode;         }         else {             Node temp = start[0];             int currPos = 1;              // Traverse to the node before the desired position             while (currPos < loc - 1) {                 temp = temp.next;                 currPos++;             }              // Insert the new node             newNode.next = temp.next;             newNode.prev = temp;             temp.next.prev = newNode;             temp.next = newNode;         }          return true;     }      public static void main(String[] args) {         // Array elements to create circular doubly linked list         int[] arr = { 1, 2, 3, 4, 5, 6 };         int n = arr.length;          // Start Pointer         Node[] start = new Node[1];         start[0] = null;          // Create the List         for (int i = 0; i < n; i++)             insertAtLocation(start, arr[i], i + 1);          // Display the list before insertion         displayList(start[0]);          // Inserting 8 at 3rd position         insertAtLocation(start, 8, 3);          // Display the list after insertion         displayList(start[0]);     } } 
Python
# Doubly linked list node class Node:     def __init__(self, data):         self.data = data         self.next = None         self.prev = None  # Function to display the list def displayList(start):     if start is None:         print("The list is empty.")         return      print("The list is: ", end="")     temp = start      while True:         print(temp.data, end=" ")         temp = temp.next         if temp == start:  # Break the loop if we have traversed the whole list             break      print()  # Function to count the number of elements in the list def countList(start):     if start is None:         return 0      count = 0     temp = start      while True:         count += 1         temp = temp.next         if temp == start:  # Break the loop if we have traversed the whole list             break      return count  # Function to insert a node at a given position def insertAtLocation(start, data, loc):     count = countList(start)      if loc < 1 or loc > count + 1:         return start      new_node = Node(data)      # If the list is empty     if start is None:         start = new_node         new_node.next = new_node         new_node.prev = new_node     # If the node is to be inserted at the beginning     elif loc == 1:         new_node.next = start         new_node.prev = start.prev         start.prev.next = new_node         start.prev = new_node         start = new_node     else:         temp = start         curr_pos = 1          # Traverse to the node before the desired position         while curr_pos < loc - 1:             temp = temp.next             curr_pos += 1          # Insert the new node         new_node.next = temp.next         new_node.prev = temp         temp.next.prev = new_node         temp.next = new_node      return start  # Driver Code if __name__ == "__main__":     # Array elements to create     # circular doubly linked list     arr = [1, 2, 3, 4, 5, 6]      # Start Pointer     start = None      # Create the List     for i in range(len(arr)):         start = insertAtLocation(start, arr[i], i + 1)      # Display the list before insertion     displayList(start)      # Inserting 8 at 3rd position     start = insertAtLocation(start, 8, 3)      # Display the list after insertion     displayList(start) 
C#
using System;  // Doubly linked list node public class Node {     public int data;     public Node next;     public Node prev; }  public class CircularDoublyLinkedList {     // Function to create a new node     public static Node GetNode(int data)     {         Node newNode = new Node{ data = data, prev = null,                                  next = null };         return newNode;     }      // Function to display the list     public static void DisplayList(Node start)     {         if (start == null) {             Console.WriteLine("The list is empty.");             return;         }          Console.Write("The list is: ");         Node temp = start;          do {             Console.Write(temp.data + " ");             temp = temp.next;         } while (temp != start);          Console.WriteLine();     }      // Function to count the number of elements in the list     public static int CountList(Node start)     {         if (start == null)             return 0;          int count = 0;         Node temp = start;          do {             count++;             temp = temp.next;         } while (temp != start);          return count;     }      // Function to insert a node at a given position     public static bool InsertAtLocation(ref Node start,                                         int data, int loc)     {         int count = CountList(start);          if (loc < 1 || loc > count + 1)             return false;          Node newNode = GetNode(data);          // If the list is empty         if (start == null) {             start = newNode;             newNode.next = newNode;             newNode.prev = newNode;         }         // If the node is to be inserted at the beginning         else if (loc == 1) {             newNode.next = start;             newNode.prev = start.prev;             start.prev.next = newNode;             start.prev = newNode;             start = newNode;         }         else {             Node temp = start;             int currPos = 1;              // Traverse to the node before the desired             // position             while (currPos < loc - 1) {                 temp = temp.next;                 currPos++;             }              // Insert the new node             newNode.next = temp.next;             newNode.prev = temp;             temp.next.prev = newNode;             temp.next = newNode;         }          return true;     }      // Driver Code     public static void Main()     {         // Array elements to create         // circular doubly linked list         int[] arr = { 1, 2, 3, 4, 5, 6 };         int n = arr.Length;          // Start Pointer         Node start = null;          // Create the List         for (int i = 0; i < n; i++)             InsertAtLocation(ref start, arr[i], i + 1);          // Display the list before insertion         DisplayList(start);          // Inserting 8 at 3rd position         InsertAtLocation(ref start, 8, 3);          // Display the list after insertion         DisplayList(start);     } } 
JavaScript
// Doubly linked list node class Node {     constructor(data) {         this.data = data;         this.next = null;         this.prev = null;     } }  // Function to display the list function displayList(start) {     if (start === null) {         console.log("The list is empty.");         return;     }      let temp = start;     let listString = "The list is: ";      do {         listString += temp.data + " ";         temp = temp.next;     } while (temp !== start);      console.log(listString); }  // Function to count the number of elements in the list function countList(start) {     if (start === null)         return 0;      let count = 0;     let temp = start;      do {         count++;         temp = temp.next;     } while (temp !== start);      return count; }  // Function to insert a node at a given position function insertAtLocation(start, data, loc) {     const count = countList(start);      if (loc < 1 || loc > count + 1)         return false;      const newNode = new Node(data);      // If the list is empty     if (start === null) {         start = newNode;         newNode.next = newNode;         newNode.prev = newNode;         return start; // Return the new start     }     // If the node is to be inserted at the beginning     else if (loc === 1) {         newNode.next = start;         newNode.prev = start.prev;         start.prev.next = newNode;         start.prev = newNode;         start = newNode;         return start; // Return the new start     }     else {         let temp = start;         let currPos = 1;          // Traverse to the node before the desired position         while (currPos < loc - 1) {             temp = temp.next;             currPos++;         }          // Insert the new node         newNode.next = temp.next;         newNode.prev = temp;         temp.next.prev = newNode;         temp.next = newNode;         return start; // Return the new start     } }  // Driver Code function main() {     // Array elements to create     // circular doubly linked list     const arr = [1, 2, 3, 4, 5, 6];     const n = arr.length;      // Start Pointer     let start = null;      // Create the List     for (let i = 0; i < n; i++)         start = insertAtLocation(start, arr[i], i + 1);      // Display the list before insertion     displayList(start);      // Inserting 8 at 3rd position     start = insertAtLocation(start, 8, 3);      // Display the list after insertion     displayList(start); }  // Call the main function main(); 

Output:-

The list is: 1 2 3 4 5 6 
The list is: 1 2 8 3 4 5 6

The time complexity :

1. `getNode` function: O(1) – It takes constant time to create a new node.

2. `displayList` function: O(n) – It traverses the entire circular doubly linked list to display its elements. Since there are n elements in the list, the time complexity is O(n).

3. `countList` function: O(n) – It also traverses the entire circular doubly linked list to count the number of elements. Therefore, the time complexity is O(n).

4. `insertAtLocation` function:
  – If the location is valid and not at the beginning: O(loc) – It traverses to the node before the desired position, which takes at most loc-1 iterations.
  – If the location is at the beginning: O(1) – It performs constant time operations to insert the new node at the beginning.
  – Counting the number of elements in the list: O(n) – It calls the `countList` function, which has a time complexity of O(n).

Overall, the time complexity of the `insertAtLocation` function is O(max(loc, n)) since it depends on the larger value between loc and the number of elements in the list.

5. `main` function:
  – Creating the circular doubly linked list: O(n) – It inserts n elements into the list using the `insertAtLocation` function, which has a time complexity of O(max(loc, n)).
  – Displaying the list: O(n) – It calls the `displayList` function, which has a time complexity of O(n).
  – Inserting 8 at the 3rd position: O(max(loc, n)) – It calls the `insertAtLocation` function, which has a time complexity of O(max(loc, n)).
  – Displaying the updated list: O(n) – It calls the `displayList` function, which has a time complexity of O(n).

Therefore, the overall time complexity of the `main` function is O(n + max(loc, n) + n) = O(max(loc, n)).

The auxiliary space complexity :- of the code is O(1) since it uses a fixed amount of additional memory regardless of the input size.



Next Article
Deletion at different positions in a Circular Linked List
author
bilal-hungund
Improve
Article Tags :
  • Advanced Data Structure
  • DSA
  • Linked List
  • circular linked list
  • doubly linked list
  • Linked Lists
  • Traversal
Practice Tags :
  • Advanced Data Structure
  • circular linked list
  • Linked List
  • Traversal

Similar Reads

  • 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 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 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 in Doubly Circular Linked List
    Circular Doubly Linked List has properties of both doubly linked list and circular linked list in which two consecutive elements are linked or connected by the previous and next pointer and the last node points to the first node by the next pointer and also the first node points to the last node by
    15+ min read
  • Deletion at different positions in a Circular Linked List
    tGiven a Circular Linked List. The task is to write programs to delete nodes from this list present at: First position.Last Position.At any given position [Tex]i [/Tex].Deleting first node from Singly Circular Linked List Examples: Input : 99->11->22->33->44->55->66 Output : 11-
    15+ min read
  • Insertion at the end in circular linked list
    A circular linked list is a data structure where each node points to the next, and the last node connects back to the first, creating a loop. Insertion at the end in circular linked list is an important operation. Understanding how to perform this insertion is essential for effectively manage and us
    7 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 in Circular Singly Linked List
    In this article, we will learn how to insert a node into a circular linked list. Insertion is a fundamental operation in linked lists that involves adding a new node to the list. In a circular linked list, the last node connects back to the first node, creating a loop. There are four main ways to ad
    12 min read
  • Insertion in an empty List in the circular linked list
    A circular linked list is a type of data structure where each node points to the next one, and the last node connects back to the first, forming a circle. This setup allows you to loop through the list without stopping. Knowing how to insert a node into an empty circular linked list is important in
    5 min read
  • Introduction to Circular Doubly Linked List
    A circular doubly linked list is defined as a circular linked list in which each node has two links connecting it to the previous node and the next node. Characteristics of Circular Doubly Linked List :A circular doubly linked list has the following properties: Circular: A circular doubly linked lis
    4 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