Write a C program to implement a Circular Singly linked list with Create and Display operation.
#include <stdio.h>
#include <stdlib.h>
// Structure of a Node
struct Node {
int data;
struct Node* next;
};
// Function to create a circular singly linked list
struct Node* createList(int n) {
struct Node *head = NULL, *temp = NULL, *newNode = NULL;
int value;
for (int i = 0; i < n; i++) {
printf("Enter value for node %d: ", i + 1);
scanf("%d", &value);
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
temp = newNode;
} else {
temp->next = newNode;
temp = newNode;
}
}
// Make the list circular
if (temp != NULL) {
temp->next = head;
}
return head;
}
// Function to display circular linked list
void displayList(struct Node* head) {
if (head == NULL) {
printf("List is empty.\n");
return;
}
struct Node* temp = head;
printf("Circular Linked List elements:\n");
do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != head);
printf("(back to head)\n");
}
// Main function
int main() {
struct Node* head = NULL;
int n;
printf("Enter number of nodes: ");
scanf("%d", &n);
head = createList(n);
displayList(head);
return 0;
}
