Delete Element from Circular Single Linked List in c

Description

This program is used create circular single linked list and to delete element from any location in the list in C

#include
#include

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

void display();
void delLoc();
void delBeg();
void delEnd();
void create();
int return_count();

void main()
{
  int choice;
  do
  {
   printf("\n__MENU__\n1.Create List\n2.Delete from location\n3...EXIT...\n");
   printf("\nENTER your choice\n");
   scanf("%d",&choice);
   switch(choice)
   {
    case 1: create();break;
    case 2 :delLoc();break;
    case 3:printf("~~~~~~~THANK YOU~~~~~~~\n");break;
   default:printf("INVALID input !!!");break;   
  }
  }while(choice!=3);
}

void create()
{
 
 int x, i,n;
 head=NULL;
 struct node* newnode,*temp;
 temp=head;
 printf("Enter no. of elements in the LIST \n");
 scanf("%d",&n);
 printf("Enter %d elements\n",n);
 for(i=0;i<n;i++)
 {
  temp=head; 
  newnode=(struct node*)malloc(sizeof(struct node*)); 
  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; 
  }
 }
 display();
}


void delLoc()
{
 int total,pos;
 struct node* temp,*pretemp;
 temp=head;
 if(head==NULL)
  display();
 else
 {
  printf("\nEnter POSITION\n");
  scanf("%d",&pos);
  total=return_count();
  
  if(pos==1)
  {
   delBeg();
   display();
  }
  
  else if(pos>total)
   printf("\nInvalid POSITION !!!! \n");
  else if(pos==total)
  {
   delEnd();
   display();
  }
  else
  {
   while(pos>=2)
   {
    pretemp=temp;
    temp=temp->next;
    pos--;
   }
   pretemp->next=temp->next;
   free(temp);
   display();
  }
 }
}

void delBeg()
{
 struct node* temp, *del;
 temp=head;
 del=head;
 if(head==NULL)
  display();
 else if(temp->next==head)
 {
  head=NULL;
  free(temp);
 }
 else
 {
  while(temp->next!=head)
   temp=temp->next;
  temp->next=head->next;
  head=head->next;
  free(del);
  
 }
}

void delEnd()
{
 struct node* temp, *pretemp;
 temp=head;
 if(head==NULL)
  display();
 else if(temp->next==head)
 {
  head=NULL;
  free(temp);  
 }
 else
 {
  while(temp->next!=head)
  {
   pretemp=temp;
   temp=temp->next;  
  }
  pretemp->next=temp->next;
  free(temp);
 }
 
}


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


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

Delete at Location Output 1 Delete at Location Output 2
Delete at Location Output 3

Leave a comment