Untitled

 avatar
unknown
plain_text
2 years ago
1.4 kB
3
Indexable
#include <stdio.h>
#include <stdlib.h>

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

// Create a circular linked list
struct Node* createCircularLinkedList(int elements[], int length) {
    if (length == 0) {
        return NULL;
    }

    struct Node* head = (struct Node*)malloc(sizeof(struct Node));
    head->data = elements[0];
    head->next = NULL;

    struct Node* current = head;

    for (int i = 1; i < length; i++) {
        struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
        new_node->data = elements[i];
        new_node->next = NULL;

        current->next = new_node;
        current = new_node;
    }

    current->next = head; // Make the last node point to the head to form a circular list

    return head;
}

// Traverse the circular linked list
void traverseCircularLinkedList(struct Node* head) {
    if (head == NULL) {
        return;
    }

    struct Node* current = head;

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

// Test the circular linked list creation and traversal
int main() {
    int elements[] = {1, 2, 3, 4, 5};
    int length = sizeof(elements) / sizeof(elements[0]);

    struct Node* circular_list = createCircularLinkedList(elements, length);
    traverseCircularLinkedList(circular_list);

    return 0;
}
Editor is loading...