Insertion at Specific Position in 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->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:
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.