Wednesday, 13 August 2014

Linked list


//Menu driven program to perform various operations in linked list

#include<iostream.h>
#include<conio.h>
#include<process.h>
struct node{
    int data;
    node *link;
  };
class linked{
     node * start;
     public:
     linked()
     {
     start=NULL;
     }
     void insert();
     void display();
     void Delete();
     void count();
     ~linked()
     {}
   };
void linked::insert()
{
   char ch;
   node* ptr=new node;
   if(ptr==NULL)
  {
    cout<<"Overflow occurs !!";
    getch();
    return;
  }
   do
  {
    node* ptr =new node;
    cout<<"\nEnter item to be inserted : ";
    cin>>ptr->data;
    ptr->link=start;
    start=ptr;
    cout<<"\nDo you wish to insert more (y/n)? : ";
    cin>>ch;
  }while(ch=='y'||ch=='Y');
}

void linked::Delete()
{
    if(start==NULL)
  {
    cout<<"Underflow ";
    getch();
    return;
  }
    node *ptr=start;
    start=ptr->link;
    delete ptr;
    cout<<"\nElement Deleted!! " ;
}

void linked::display()
{
    node *ptr=start;
    if(ptr!=NULL)
   {
     cout<<"\nList is : ";
     while(ptr!=NULL)
   {
     cout<<ptr->data<<"  ";
     ptr=ptr->link;
   }
}
    else
    cout<<"\nFirst insert some elements!!";
}

void linked::count()
{
    node *ptr= start;
    int c=0;
    while(ptr!=NULL)
   {
     c++;
     ptr=ptr->link;
   }
    cout<<"\nNumber of nodes in linked list is : "<<c;
}

void menu()
{
   cout<<"\n\t\tMain Menu\n\n"
       <<"\tPress 1 : To Insert element "
       <<"\n\tPress 2 : To Delete element "
       <<"\n\tPress 3 : To display list"
       <<"\n\tPress 4 : To count nodes"
       <<"\n\tPress 5 : To Exit";
}
void main()
{
    int n,i,opt,f=0;
    char ch;
    linked l;
    do
   {
    clrscr();
    menu();
    cout<<"\n\n\tEnter your option : ";
    cin>>opt;
    switch(opt)
   {
     case 1: clrscr();
        l.insert();
        f++;
        break;
     case 2: clrscr();
         l.Delete();
         break;
     case 3: clrscr();
         l.display();
         getch();
         break;
     case 4: clrscr();
         l.count();
         break;
     case 5: cout<<"\n\tProgram Terminating...";
        getch();
        exit(0);
        break;
     default : cout<<"\n\tInvalid option!!";
          getch();
   }
       cout<<"\n\n\tDo you wish to try more options(n/y)? ";
       cin>>ch;
  }   while(ch=='y'||ch=='Y');
       getch();
}

















No comments:

Post a Comment