DATA STRUCTURES PROGRAM • DOUBLY & CIRCULAR LINKED LISTS

Insert at the Beginning of a Circular Linked List

Learn how to insert at the beginning of a circular linked list using a clear C program.

IntermediateCircular linked listTail pointerdo-while

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
10 20 30

COMPLETE C PROGRAM

Complete C implementation

dsa-insert-circular-list-beginning.c
Open in compiler
#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, 20); cappend(&tail, 30);
    struct CNode *node = new_cnode(10);
    node->next = tail->next;
    tail->next = node;
    cprint(tail);
    cfree(tail);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

10 20 30
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Insert between the tail and current head without changing the tail pointer.
  3. Display the computed result.

Insert between the tail and current head without changing the tail pointer.

EFFICIENCY

Time and space complexity

Time complexity

O(1)

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.