Insert Node At The Beginning of The Circular Linked List In C

Hello Coders! In this post, we will talk about how to insert node at the beginning of the circular linked list.

How To Insert Node At The Beginning of The Circular Linked List In C ?

struct node{
    int data;
    struct node *next;
};
struct node *head = NULL;

void insertAtBeginning(int a){
    struct node *new = malloc(sizeof(struct node));
    new->data = a;

    if(head==NULL){
        new->next=new;
        head = new;

    }

    else{

        struct node *temp = head;
        while (temp->next!=NULL)

        {
            temp = temp->next;
        }

        temp->next = new;
        new->next = head;
        head = new;  

    }
}

In this code we are doing following things:

  1. If linked list is empty then make the node as head and its next pointer points to itself.
  2. Else make a new pointer say temp which iterates from first to last node.
  3. Then insert the node at the end of the linked list and make the last node as head which points to previous head.
  4. So this is how we insert a new node at the beginnig of the circular linked list.

So this is how the function is working.

#include<stdio.h>
#include<stdlib.h>

struct node{
    int data;
    struct Node *next;
};
struct node *head = NULL;

void insertAtBeginning(int a)
{
    struct node *new = (struct node *)malloc(sizeof(struct node));
    new->data = a;
    new->next = head;

   struct node *temp = head;
    if (head != NULL)
    {
        while (temp->next != head)
            temp = temp->next;
            temp->next = new;
    }
    else{
        new->next = new;
        head = new;
    }
}

void print()
{
    struct node *temp = head;
    if (head != NULL)
    {
        do
        {
            printf("%d ", temp->data);
            temp = temp->next;
        }
        while (temp != head);
    }
}

int main()
{
    insertAtBeginning(1);
    insertAtBeginning(2);
    insertAtBeginning(3);
    print();

   return 0;
}

If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment