Friday, August 31, 2012

C Program for Circular Link List

/*Creating Circular Link List*/
#include<iostream.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int item;
struct node *add;
}*last,*start;
//---------
void creat(struct node *q)
{
  if(q==NULL)
  {
    start=(node*)malloc(sizeof(node));
    q=start;
  }
  cout<<"\nEnter Value.:";
  cin>>q->item;
  cout<<"Continue 1.Yes/2.NO.:";
  int choice;
  cin>>choice;
  if(choice==1)
  {
    q->add=(node*)malloc(sizeof(node));
    creat(q->add);
  }
  else
  {
   last=q;
    last->add=start;
  }
}
//-----------
void print(struct node *q)
{
 cout<<" "<<q->item;
 if(q==last)return;
 print(q->add);
}
//------------
void ins(struct node *q,int num)
{
 struct node *t1,*t2;
 t2=(node*)malloc(sizeof(node));
 t2->item=num;
 if(q->item>num)
 {
  t2->add=start;
  start=t2;
 }
 else if(last->item<num)
 {
   last->add=t2;
   last=t2;
   last->add=start;
 }
 else
 {
  t1=q;
  while(q->item<num&&q!=last)
  { t1=q;q=q->add;}
  t2->add=t1->add;
  t1->add=t2;
 }
}
void del(node *q,int num)
{
 if(q->item==num)
 {
  start=start->add;
  free(q);
  return;
 }
 node *t1;
 t1=q;
 q=q->add;
 while(q->item!=num&&q!=start)
 { t1=q;q=q->add;}
 if(q==start)
 {
  cout<<"\nNot Found";
  return;
 }
 if(q==last)
 {
  last=t1;
  last->add=start;
 }
 else
 { t1->add=q->add;}

 free(q);
}
void main()
{
clrscr();
start=NULL;
cout<<"\nEnter List in Incresing Order\n";
creat(start);
print(start);
cout<<"\nEnter Value To Insert";
int x;
cin>>x;
ins(start,x);
cout<<"After Inserting";
print(start);
cout<<"\nEnter Value To Delete";
cin>>x;
del(start,x);
cout<<"After Deleting";
print(start);
getch();
}

No comments:

Post a Comment