C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Circular Linked List Creation and Traversal

C Program: Circular Linked List Creation and Traversal

C

#include <stdio.h>

#include <stdlib.h>

 

// Structure definition

struct Node {

    int data;

    struct Node *next;

};

 

// Function to create a new node

struct Node* createNode(int data) {

    struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));

    newNode->data = data;

    newNode->next = NULL;

    return newNode;

}

 

// Function to create a circular linked list

struct Node* createCircularList(int n) {

    struct Node *head = NULL, *temp, *newNode;

    int data, i;

 

    if (n <= 0) {

        printf("Number of nodes must be greater than 0.\n");

        return NULL;

    }

 

    for (i = 1; i <= n; i++) {

        printf("Enter data for node %d: ", i);

        scanf("%d", &data);

        newNode = createNode(data);

 

        if (head == NULL) {

            head = newNode;

            temp = head;

        } else {

            temp->next = newNode;

            temp = newNode;

        }

    }

    temp->next = head; // make it circular

    return head;

}

 

// Function to display circular linked list

void displayCircularList(struct Node *head) {

    struct Node *temp = head;

 

    if (head == NULL) {

        printf("\nList is empty.\n");

        return;

    }

 

    printf("\nCircular Linked List: ");

    do {

        printf("%d -> ", temp->data);

        temp = temp->next;

    } while (temp != head);

    printf("(back to head)\n");

}

 

int main() {

    struct Node *head = NULL;

    int n;

 

    printf("Enter number of nodes: ");

    scanf("%d", &n);

 

    head = createCircularList(n);

 

    displayCircularList(head);

 

    return 0;

}

Output

 
OUTPUT :

Enter number of nodes: 5
Enter data for node 1: 10
Enter data for node 2: 20
Enter data for node 3: 30
Enter data for node 4: 40
Enter data for node 5: 50

Circular Linked List: 10 -> 20 -> 30 -> 40 -> 50 -> (back to head)

Explanation

Step

Description

Step 1

Create n nodes dynamically using malloc().

Step 2

Connect each node’s next pointer to form a normal singly linked list.

Step 3

Make the last node’s next pointer point back to head — this makes it circular.

Step 4

Use a do...while loop for traversal to ensure every node is printed once.