Powered By Blogger

Friday, July 15, 2011

CIRCULAR LINKED LIST:

#include<iostream.h>
#include<conio.h>
class LinkedList
{ struct node
  {int data;
   node *link;
  }*front,*rear;
  int size;
  public:
    LinkedList() { front=rear=NULL;size=0;}
    void addNodeAtEnd(int item);
    void addNodeAtBegin(int item);
    void addNodeAtPos(int pos,int item);
    void display();
    void reverse();
    ~LinkedList();
};
void LinkedList:: addNodeAtEnd(int item)
{
  node *temp=new node;
  temp->data=item;
  if ((front==NULL)&&(rear==NULL))
{front=temp;
front->link=front;
}
  else
{ temp->link=front;
  rear->link=temp;
}
  rear=temp;++size;
}
void LinkedList::addNodeAtBegin(int item)
{node *temp=new node;
 temp->data=item;
 if ((front==NULL)&&(rear==NULL))
{front=temp;
front->link=front;
}
  else
{ temp->link=front;
  rear->link=temp;
  front = temp;
}
  ++size;
}


void LinkedList::addNodeAtPos(int pos,int item)
{ node *r=front;node *temp;
  if ( (pos>1)&&(pos<size)&&(size>1) )
  { for (int i=1;i<pos-1;i++) r=r->link;
    temp=new node;temp->data=item;
    temp->link=r->link;r->link=temp;++size;
  }
  else cout<<"\nOut of Boundary...\n";
}
void LinkedList:: display()
{


   node *r=front;
   while (r!=rear){  cout.width(5);
    cout<<r->data;
    r=r->link;
  }
   cout.width(5);
   cout<<r->data;
}


LinkedList::~LinkedList()
{  node *temp;
while(front!=rear)
{ temp=front;
  front=front->link;
  rear->link=front;
  delete temp;
 }
 delete front;
}
void main()
{
  clrscr();
  LinkedList s;
  int n,m,p;
  do
  {
  cout<<"\n";
  cout<<"\n1. Add Node At End\n";
  cout<<"\n2. Add Node At Begin\n";
  cout<<"\n3. Add Node Between Front and Rear\n";
  cout<<"\n4. Display\n";
  cout<<"\n5. Exit\n";
  cout<<"\n Enter Your Choice...";cin>>n;




  switch (n)
  { case 1: {   cout<<"\n Enter data to be add ";cin>>m;
s.addNodeAtEnd(m);break;}
    case 2: {    cout<<"\n Enter data to be add ";cin>>m;
s.addNodeAtBegin(m);break;}
    case 3: {cout<<"\n Enter Position";cin>>p;
     cout<<"\n Enter data to be add ";cin>>m;
    s.addNodeAtPos(p,m);break;}
    case 4: {s.display();break;}
    case 5: {return;}
    default: {cout<<"\n Sorry...\n";break;}
  }
 clrscr();
 cout<<"Output: ";
 s.display();
 }while (n<=5);
}

No comments:

Post a Comment