DS Practical Slip 6 Q A

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

  1. Define a structure for a node with:
    • data
    • next pointer
  2. For each new node:
    • Allocate memory using malloc().
    • If list is empty:
      • Make head point to the new node.
      • Point newnode->next to head.
    • Otherwise:
      • Traverse to the last node.
      • Link last node’s next to new node.
      • Link newnode->next to head to maintain circularity.

🔹 Display Operation

  1. Start from head.
  2. Traverse using next pointer.
  3. Stop when we reach head again.
  4. 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.

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top