Saturday 11 January 2014

program in C++ to create a linked list

A program in C++ to create a  linked list  with insert_front and delete_front as member functions by creating to objects. Use constructor to initialize the objects.

#include<iostream.h>
#include<conio.h>
struct node
{int info;
 struct node *next;
};
typedef struct node node;
class Linklist
{

private:node *first;
 public:void insert_front();
            void delete_front();
            void display();
            Linklist()
            {first=NULL;
            }
};
void main()
{int a;
 clrscr();
 Linklist obj;
 while (a!=4)
 {clrscr();
  cout<<"\n  1.INSERT IN FRONT\n  2.DELETE FROM FRONT\n  3.DISPLAY LINKLIST\n  4.EXIT\n";
  cout<<"\n  ENTER THE CHOICE:";
  cin>>a;
  switch(a)
  {case 1:obj.insert_front();
              break;
   case 2:obj.delete_front();
              break;
   case 3:obj.display();
              break;
   case 4:cout<<"\n thanks for using the program";
              getch();
              break;
   default:cout<<"\n sorry you have entered wrong choice enter again:";
               getch();
  };
  getch();
 }
}
void Linklist::insert_front()
{node *temp;
 temp=new(node);
 if(temp==0)
 {cout<<"\n  MEMORY OVERFLOW";
  return;
 }
 cout<<"\n  ENTER THE NUMBER AT THE NODE:";
 cin>>temp->info;
 if(first==NULL)
 {first=temp;
  temp->next=NULL;
  return;
 }
 temp->next=first;
 first=temp;
}
void Linklist::delete_front()
{node *ptr;
 if (first==NULL)
 {cout<<"\n  UNDERFLOW";
 }
 else
 {ptr=first;
  first=first->next;
  cout<<"\n"<<"\t\t"<<ptr->info<<" DELETED";
  delete ptr;
 }
}
void Linklist::display()
{node *ptr;
 ptr=first;
 while(ptr!=NULL)
 {cout<<"\n"<<"\t\t"<<ptr->info;
  cout<<endl;
  ptr=ptr->next;
 }
}

No comments:

Post a Comment