Linked List In C++ Using Class




class list {

struct node
   {
    int x;
node *next;
   };
   node *head;
 
  public:

   list();
   ~list();
   void insert(int);
   void show();
   void search();
   void update();
   void del();
 };

                    // constructor

list::list()
{

head=0;

}

                     // add data function

void list::insert(int a)
 {

 node *ptr1;
 ptr1=new node;
 ptr1->x=a;
 ptr1->next=0;

 node *temp;
 temp=head;
 if (temp!=0)
  {
  while (temp->next!=0)
  temp=temp->next;

  temp->next=ptr1;
  }
 else
 head=ptr1;

 }

                 // destractor

list::~list()

 {

  if(head!=0)
    {
    node *ptr=0;
ptr=head;

while(head!=0)
  {
head=head->next;
delete ptr;
ptr=head;


  }
}

 }

               // show function

void list::show()
 {

 node *temp;
 temp=head;
 if (temp!=0)
  {

  while (temp!=0)
 
    {


  cout<<"Class :"<<temp->x<<endl;


  temp=temp->next;
    }
  }
  else
  {

  cout<<"\n---- Empty list ---- \n";
  }
 }
void list::del() {
 int dta;
 cout<<"Enter Roll Number : ";
 cin>>dta;
    
    node *pre=0,*del=0;
if (head->x==dta)
{
del=head;
head=del->next;
delete del;
return ;
}
// search all nodes
pre=head;
del=head->next;
while(del!=0)
{
if (del->x.rol==dta)
{
pre->next= del->next;
 
delete del;
break;
}
pre=del;
del=del->next;
}
}

1 comment: