C Program to Implement Circular Singly Linked List (Create and Display)
A Circular Singly Linked List (CSLL) is a variation of a linked list where the last node points back to the first node instead of NULL. This allows circular traversal of the list. In this program, we will implement Create and Display operations in a simple, student-friendly way.
📝 Problem Statement
Q1. A) Write a C program to implement a Circular Singly Linked List with Create and Display operation.
💡 Logic (Simple Steps)
🔹 Create Operation
- Define a structure for a node with:
datanextpointer
- For each new node:
- Allocate memory using
malloc(). - If list is empty:
- Make
headpoint to the new node. - Point
newnode->nexttohead.
- Make
- Otherwise:
- Traverse to the last node.
- Link last node’s
nextto new node. - Link
newnode->nexttoheadto maintain circularity.
- Allocate memory using
🔹 Display Operation
- Start from
head. - Traverse using
nextpointer. - Stop when we reach
headagain. - Print each node’s data.
💻 Source Code (Student-Friendly)
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head = NULL, *newnode, *temp;
int n, i, value;
printf("Enter number of nodes: ");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
printf("Enter value: ");
scanf("%d", &value);
newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = value;
newnode->next = NULL;
if(head == NULL)
{
head = newnode;
newnode->next = head; // Point to itself
}
else
{
temp = head;
while(temp->next != head)
temp = temp->next;
temp->next = newnode;
newnode->next = head;
}
}
printf("Circular Linked List elements are:\n");
temp = head;
if(head != NULL)
{
do
{
printf("%d ", temp->data);
temp = temp->next;
} while(temp != head);
}
return 0;
}
🖥️ Sample Output
Enter number of nodes: 4
Enter value: 10
Enter value: 20
Enter value: 30
Enter value: 40
Circular Linked List elements are:
10 20 30 40
🎓 Viva Questions with Answers
1. What is a Circular Singly Linked List?
A linked list where the last node points back to the first node instead of NULL.
2. What is the advantage of a circular linked list?
It allows circular traversal without checking for NULL.
3. What does the head pointer represent?
It points to the first node of the circular linked list.
4. How do you know when to stop traversal?
Stop when the next node becomes head again.
5. Which function is used to allocate memory dynamically?
malloc() is used.
