Untitled

 avatar
unknown
plain_text
a month ago
1.6 kB
2
Indexable
#include<stdio.h>
#include<stdlib.h>


// Define a node structure
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// Function to create a new node
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (!newNode) {
        printf("Memory allocation failed\n");
        exit(1);
    }
    newNode->data = data;
    newNode->next = newNode; // Point to itself initially
    return newNode;
}

// Function to add a node to the circular linked list
void addNode(Node** tail, int data) {
    Node* newNode = createNode(data);

    if (*tail == NULL) {
        // If list is empty, create the first node
        *tail = newNode;
    } else {
        // Insert the new node after the tail and make it the new tail
        newNode->next = (*tail)->next;
        (*tail)->next = newNode;
        *tail = newNode;
    }
}

// Function to print all elements of the circular linked list
void printList(Node* tail) {
    if (tail == NULL) {
        printf("The list is empty.\n");
        return;
    }

    Node* current = tail->next;
    printf("Current elements in the list: ");
    do {
        printf("%d ", current->data);
        current = current->next;
    } while (current != tail->next);
    printf("\n");
}

// Main function to test the circular linked list
int main() {
    Node* tail = NULL; // Initialize the tail pointer to NULL

    // Adding elements to the list
    addNode(&tail, 10);
    addNode(&tail, 20);
    addNode(&tail, 30);

    // Printing the list
    printList(tail);

    return 0;
}
Leave a Comment