Insert at Location in Circular Single Linked List using C

Description

This program is used to Insert element at Specified Location in Circular Single Linked List using C.

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

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

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);
 }
}
void insLoc()
{
 int pos,total;
 struct node* temp,*newnode;
 temp=head;
 printf("\nEnter POSITION\n");
 scanf("%d",&pos);
 if(pos==1)
 {
  insBeg();
 }
 else
 {
  total=return_count();
  if(pos>(total+1))
  printf("\nInvalid POSITION !!!!\n");
  else
  {
   if(pos==(total+1))
   {
    insEnd();
   }
   else
   {
    newnode=(struct node*)malloc(sizeof(struct node*)); 
    printf("\nEnter element\n");
    scanf("%d",&newnode->data);
    while(pos>2)
    {
     temp=temp->next;
     pos--;
    }
    newnode->next=temp->next;
    temp->next=newnode;
   }
   
  }
 }
 display();
}

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; 
  
 }
}

void insEnd()
{
 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;
  temp->next=newnode;
  newnode->next=head; 
 }
}

int return_count()
{
 int i = 1;
 struct node* temp;
 temp=head;
 if(head==NULL)
 return 1;
 while(temp->next!=head)
 {
  temp=temp->next;
  i++;
 }
 return i;
}

OUTPUT

insert at loc Circular single linked list Output 1 insert at loc Circular single linked list Output 2
insert at loc Circular single linked list Output 3

Labels: