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 node just before the given position at which 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
- Assgin (temp->next)->prev as newNode->next
Below is the implementation of the above idea:
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, O(n) => Inserting the elements. So, total complexity is O(n + n) = O(n)
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Doubly Circular Linked List | Set 1 (Introduction and Insertion)
- Insertion Sort for Doubly Linked List
- Doubly Linked List | Set 1 (Introduction and Insertion)
- Circular Singly Linked List | Insertion
- Insert a node at a specific position in a linked list
- Doubly Circular Linked List | Set 2 (Deletion)
- Reverse a doubly circular linked list
- Insertion in a sorted circular linked list when a random pointer is given
- Convert an Array to a Circular Doubly Linked List
- Search an Element in Doubly Circular Linked List
- Delete a Doubly Linked List node at a given position
- Convert a given Binary Tree to Circular Doubly Linked List | Set 2
- Remove all even parity nodes from a Doubly and Circular Singly Linked List
- Circular Queue | Set 2 (Circular Linked List Implementation)
- Convert a Binary Tree to a Circular Doubly Link List
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- Difference between Singly linked list and Doubly linked list
- Convert singly linked list into circular linked list
- Construct a Doubly linked linked list from 2D Matrix
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.