Implement a circular linked list and perform insertion, deletion, and traversal in C

 #include <stdio.h>

#include <stdlib.h>


struct Node {

    int data;

    struct Node* next;

};


struct Node* head = NULL;


// Function to insert at the end

void insert(int data) {

    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

    newNode->data = data;


    if (head == NULL) {

        head = newNode;

        newNode->next = head;

    } else {

        struct Node* temp = head;

        while (temp->next != head) {

            temp = temp->next;

        }

        temp->next = newNode;

        newNode->next = head;

    }

}


// Function to delete a node by value

void delete(int key) {

    if (head == NULL) {

        printf("List is empty.\n");

        return;

    }


    struct Node *current = head, *prev = NULL;


    // If head needs to be deleted

    if (head->data == key) {

        // Only one node

        if (head->next == head) {

            free(head);

            head = NULL;

            return;

        }


        // More than one node

        struct Node* last = head;

        while (last->next != head) {

            last = last->next;

        }

        last->next = head->next;

        struct Node* temp = head;

        head = head->next;

        free(temp);

        return;

    }


    // Deleting node other than head

    prev = head;

    current = head->next;

    while (current != head) {

        if (current->data == key) {

            prev->next = current->next;

            free(current);

            return;

        }

        prev = current;

        current = current->next;

    }


    printf("Node with value %d not found.\n", key);

}


// Function to traverse the list

void traverse() {

    if (head == NULL) {

        printf("List is empty.\n");

        return;

    }


    struct Node* temp = head;

    printf("List elements: ");

    do {

        printf("%d ", temp->data);

        temp = temp->next;

    } while (temp != head);

    printf("\n");

}


// Main function to test the list

int main() {

    insert(10);

    insert(20);

    insert(30);

    traverse();  // Output: 10 20 30


    delete(20);

    traverse();  // Output: 10 30


    delete(10);

    traverse();  // Output: 30


    delete(30);

    traverse();  // Output: List is empty


    return 0;

}

Output:


Comments