DATA STRUCTURES PROGRAM • DOUBLY & CIRCULAR LINKED LISTS
Create and Traverse a Circular Linked List
Learn how to create and traverse a circular linked list using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
10 20 30
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <stdlib.h>
struct CNode { int data; struct CNode *next; };
struct CNode *new_cnode(int value)
{
struct CNode *node = malloc(sizeof *node);
if (node == NULL) exit(EXIT_FAILURE);
node->data = value; node->next = node;
return node;
}
void cappend(struct CNode **tail, int value)
{
struct CNode *node = new_cnode(value);
if (*tail == NULL) { *tail = node; return; }
node->next = (*tail)->next;
(*tail)->next = node;
*tail = node;
}
void cprint(const struct CNode *tail)
{
if (tail == NULL) { putchar('\n'); return; }
const struct CNode *current = tail->next;
do { printf("%d ", current->data); current = current->next; } while (current != tail->next);
putchar('\n');
}
void cfree(struct CNode *tail)
{
if (tail == NULL) return;
struct CNode *head = tail->next;
tail->next = NULL;
while (head != NULL) { struct CNode *next = head->next; free(head); head = next; }
}
int main(void)
{
struct CNode *tail = NULL;
cappend(&tail, 10); cappend(&tail, 20); cappend(&tail, 30);
cprint(tail);
cfree(tail);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
10 20 30
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Start at tail->next and stop only after returning to the same head node.
- Display the computed result.
Start at tail->next and stop only after returning to the same head node.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
