Insert at Beginning in Circular Single Linked List Using C

Description

This program is used to insert element at the beginning of Circular Single Linked List Using C.

#include<stdio.h>
#include<stdlib.h>
struct node
{
 int data;
 struct node * next;
};
struct node *head=NULL;
void display();
void insBeg();

void main()
{
  int choice;
  do
  {
   printf("\n__MENU__\n1.Insert at the Beginning\n2...EXIT...\n");
   printf("\nENTER your choice\n");
   scanf("%d",&choice);
   switch(choice)
   {
    case 1 :insBeg();break;
    case 2:printf("~~~~~~~THANK YOU~~~~~~~\n");break;
   default:printf("INVALID input !!!");break;   
  }
  }while(choice!=2);
}

void insBeg()
{
 struct node* temp,*newnode;
 temp=head;
 newnode=(struct node*)malloc(sizeof(struct node*)); 
 printf("\nEnter element\n");
 scanf("%d",&newnode->data);
 if(head==NULL)
 {
  head=newnode;
  newnode->next=head;
 }
 else
 {
  while(temp->next!=head)
   temp=temp->next;
  newnode->next=temp->next;
  temp->next=newnode;
  head=newnode; 
  
 }
 display();
}
void display()
{
 struct node* temp;
 temp=head;
 if(head==NULL)
  printf("List is empty !!!");
 else 
 {
  printf("List elements are :\t");
  while(temp->next!=head)
  {
   printf("%d\t",temp->data);
   temp=temp->next;
  }
  printf("%d\n",temp->data);
 }
}

OUTPUT

Insert at beg Circular Linked List Output 1 Insert at beg Circular Linked List Output 2

Labels: