Deletion in Doubly Circular Linked List
We have discussed the doubly circular linked list introduction and its insertion.
Let us formulate the problem statement to understand the deletion process. Given a ‘key’, delete the first occurrence of this key in the circular doubly linked list.
Case 1: Empty List(start = NULL)
- If the list is empty, simply return it.
Case 2: The List initially contains some nodes, start points at the first node of the List
- If the list is not empty, then we define two pointers curr and prev_1 and initialize the pointer curr points to the first node of the list, and prev_1 = NULL.
- Traverse the list using the curr pointer to find the node to be deleted and before moving from curr to the next node, every time set prev_1 = curr.
- If the node is found, check if it is the only node in the list. If yes, set start = NULL and free the node pointing by curr.
- If the list has more than one node, check if it is the first node of the list. The condition to check this is (curr == start). If yes, then move prev_1 to the last node(prev_1 = start -> prev). After prev_1 reaches the last node, set start = start -> next and prev_1 -> next = start and start -> prev = prev_1. Free the node pointing by curr.
- If curr is not the first node, we check if it is the last node in the list. The condition to check this is (curr -> next == start). If yes, set prev_1 -> next = start and start -> prev = prev_1. Free the node pointing by curr.
- If the node to be deleted is neither the first node nor the last node, declare one more pointer temp and initialize the pointer temp points to the next of curr pointer (temp = curr->next). Now set, prev_1 -> next = temp and temp ->prev = prev_1. Free the node pointing by curr.
- If the given key(Say 4) matches with the first node of the list(Step 4):
- If the given key(Say 8) matches with the last node of the list(Step 5):
- If the given key(Say 6) matches with the middle node of the list(Step 6):
List Before Deletion: 4 5 6 7 8 List doesn't have node with value = 9 List After Deletion: 4 5 6 7 8 List After Deleting 4: 5 6 7 8 List After Deleting 8: 5 6 7 List After Deleting 6: 5 7
Time Complexity: O(n), as we are using a loop to traverse n times (for deletion and displaying the linked list). Where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.
This article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.