Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
2.2 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

// Function to delete a node from a circular linked list
void deleteNode(struct Node** head, int key) {
    if (*head == NULL) { // List is empty
        printf("List is empty. Cannot delete node.\n");
        return;
    }

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

    // Find the node to be deleted and its previous node
    while (current->data != key) {
        if (current->next == *head) { // Node not found, key doesn't exist
            printf("Node with key %d does not exist in the list.\n", key);
            return;
        }
        prev = current;
        current = current->next;
    }

    // Check if the node to be deleted is the only node in the list
    if (current->next == *head) {
        *head = NULL;
        free(current);
        return;
    }

    // Check if the node to be deleted is the first node (head)
    if (current == *head) {
        prev = *head;
        while (prev->next != *head) {
            prev = prev->next;
        }
        prev->next = (*head)->next;
        *head = (*head)->next;
        free(current);
    }
    else {
        prev->next = current->next;
        free(current);
    }
}

// Function to print the circular linked list
void printList(struct Node* head) {
    if (head == NULL) {
        printf("List is empty.\n");
        return;
    }

    struct Node* current = head;

    do {
        printf("%d ", current->data);
        current = current->next;
    } while (current != head);
    printf("\n");
}

// Function to create a new node
struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

int main() {
    struct Node* head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);
    head->next->next->next = createNode(4);
    head->next->next->next->next = head; // Make it circular

    printf("Original list: ");
    printList(head);

    deleteNode(&head, 3); // Delete node with key 3

    printf("List after deletion