Insertion at Specific Position in a Circular Doubly Linked List
Last Updated :
11 Jul, 2025
Prerequisite:
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->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>
OutputThe 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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem