Hello,
         To make linked list efficient, we make circular linked list......
circular linked list in c

  • CIRCULAR LINKED LIST 

 
       written by techsayright

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

struct node
{
 int info;
 struct node *next;
}*first=NULL,*temp=NULL,*newnode=NULL,*t=NULL;

struct node* createnode()
{
 int x;
 struct node*temp;
 temp=(struct node*)malloc(sizeof(struct node));
 printf("\nEnter value:");
 scanf("%d",&x);
 if(temp!=NULL)
 {
  temp->info=x;
  temp->next=NULL;
  return temp;
 }
 else
 {
  printf("\nMemory not allocated");
  return 0;
 }
}

void display()
{
 if(first!=NULL)
 {
  for(temp=first;temp->next!=first;temp=temp->next)
  printf("%d->",temp->info);
  printf("%d->NULL",temp->info);
 }
 else
  printf("\nLinked list is empty");
}

int count()
{
 int i;
 for(temp=first,i=0;temp->next!=first;i++,temp=temp->next);
 i++;
 return i;
}

void ias()
{
 newnode=createnode();
 if(first==NULL)
 {
  first=newnode;
  first->next=first;
 }
 else
 {
  int p,i;
  printf("Enter Position: ");
  scanf("%d",&p);
  
  if(p<=0 || p>count())
   printf("Enter position in range");
  else if(p==count())
  {
   for(temp=first,i=1;i<p;i++,temp=temp->next);
   temp->next=newnode;
   newnode->next=first;
  }
  else
  {
   for(temp=first,i=1;i<p;i++,temp=temp->next);
   newnode->next=temp->next;
   temp->next=newnode;
  }
 }
 display();
}

void ial()
{
 newnode=createnode();
 if(first==NULL)
 {
  first=newnode;
  first->next=newnode;
 }
 else
 {
  for(temp=first;temp->next!=first;temp=temp->next);
  temp->next=newnode;
  newnode->next=first;
 }
 display();
}


void daf()
{
 if(first->next==first)
 {
  first=NULL;
 }
 else
 {
  for(temp=first;temp->next->next!=first;temp=temp->next);
  temp->next->next=first->next;
  t=first;
  first=first->next;
  free(t);
 }
 display();
}

void dal()
{
 if(first==NULL)
  printf("Empty List");
 else if(first->next==first)
 {
  first=NULL;
 }
 else
 {
  for(temp=first;temp->next->next!=first;temp=temp->next);
  t=temp->next;
  temp->next=first;
  free(t);
 }
 display();
}


void main()
{
 int c;
 do
 {
  printf("\nMENU\n1.Insert at Specified\n2.Insert at last\n3.Delete at first\n4.Delete last\n5.Display LL\n6.Exit\n\n");
  scanf("%d",&c);
  switch(c)
  {
   case 1:
    ias();
    break;
   case 2:
    ial();
    break;
      case 3:
    daf();
    break;
   case 4:
    dal();
    break;
   case 5:
    display();
    break;
   case 6:
    exit(0);
   default :
    printf("\nenter valid choice");
  }
 }whhile(c!=6);
 getch();
}



happy coding✌

Post a Comment

Hii

Previous Post Next Post