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:
// 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;
} |
// 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 |
# 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# 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 */ |
<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
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:
#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 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 ]);
}
} |
# 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)
|
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);
}
} |
// 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.