Algorithm for Deleting a Node in a Circular Linked List
Algorithm for Deleting a Node in a Circular Linked List
o If the node is found, update the next pointer of the previous node to skip the node to
be deleted.
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
};
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
newNode->next = newNode;
*head = newNode;
} else {
temp = temp->next;
temp->next = newNode;
newNode->next = *head;
if (*head == NULL) {
printf("List is empty.\n");
return;
free(current);
*head = NULL;
return;
if ((*head)->data == key) {
last = last->next;
last->next = (*head)->next;
*head = (*head)->next;
free(temp);
return;
do {
prev = current;
current = current->next;
if (current->data == key) {
prev->next = current->next;
free(current);
return;
}
if (head == NULL) {
printf("List is empty.\n");
return;
do {
temp = temp->next;
printf("(Head)\n");
// Main function
int main() {
// Insert elements
insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
insertAtEnd(&head, 40);
display(head);
// Delete nodes
deleteNode(&head, 10);
display(head);
deleteNode(&head, 30);
display(head);
return 0;
Explanation
o If the list is empty, sets next to itself and makes it the head.
o Otherwise, finds the last node and links it to the new node.
o If the list has only one node, frees the node and sets head = NULL.
o If the node to delete is the head, finds the last node, updates head, and frees the old
node.
o Otherwise, traverses the list to find the node, updates the next pointer of the
previous node, and frees the target node.
Output
Key Points