Insertion at Specific Position in a Circular Doubly Linked List

23 Jun, 2022
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. 
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:  
Create a newNode in the memory.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.Insert the new node by performing below operations: Assign newNode->next = temp->nextAssign newNode->prev as temp->nextAssign temp->next as newNodeAssign (temp->next)->prev as newNode->next
Create a newNode in the memory.
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.
Insert the new node by performing below operations: Assign newNode->next = temp->nextAssign newNode->prev as temp->nextAssign temp->next as newNodeAssign (temp->next)->prev as newNode->next
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++
Java
Python3
C#
Javascript
// 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 nodestruct node {    int data;    struct node* next;    struct node* prev;}; // Utility function to create a node in memorystruct node* getNode(){    return ((struct node*)malloc(sizeof(struct node)));} // Function to display the listint 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 listint 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 listbool 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 elementsvoid 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 Codeint 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 program to convert insert// an element at a specific position// in a circular doubly linked listing,// end and middleclass GFG{ // Doubly linked list nodestatic class node{    int data;    node next;    node prev;}; // Utility function to create a node in memorystatic node getNode(){    return new node();} // Function to display the liststatic int displayList( node temp){    node t = temp;    if (temp == null)        return 0;    else    {        System.out.println( "The list is: ");         while (temp.next != t)        {            System.out.print( temp.data + " ");            temp = temp.next;        }         System.out.println( temp.data );         return 1;    }} // Function to count number of// elements in the liststatic 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 liststatic 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 elementsstatic 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 Codepublic 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 = 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 Arnab Kundu
# Python3 program to insert an element# at a specific position in a# circular doubly linked list # Node of the doubly linked listclass Node:         def __init__(self, data):        self.data = data        self.prev = None        self.next = None # Utility function to create# a node in memorydef getNode():     return (Node(0)) # Function to display the listdef 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 listdef 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 listdef 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 elementsdef 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 Codeif __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# program to convert insert// an element at a specific position// in a circular doubly linked listing,// end and middleusing System; class GFG{ // Doubly linked list nodepublic class node{    public int data;    public node next;    public node prev;}; // Utility function to create a node in memorystatic node getNode(){    return new node();} // Function to display the liststatic 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 liststatic 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 liststatic 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 elementsstatic 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 Codepublic 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 */
<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>
The list is: 1 2 3 4 5 6
The list is: 1 2 8 3 4 5 6
 
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. 
andrew1234
princiraj1992
nidhi_biet
rdtank
sagar0719kumar
abhishek0719kadiyan
rohan07
circular linked list
doubly linked list
Linked Lists
Traversal
Advanced Data Structure
Linked List
Linked List
Traversal
circular linked list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)
Ordered Set and GNU C++ PBDS
2-3 Trees | (Search, Insert and Deletion)
Extendible Hashing (Dynamic approach to DBMS)
Segment Tree | Set 2 (Range Minimum Query)
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)