Friday, 2 September 2011

Deleting the linked list (all the nodes)

 //erase() function logic for Single Linked List
template<class T>
void sll<T>::erase()
{
 node<T> *p;
 while(!isempty())
 {
  p=first;
  first=first->link;
  delete p;
 }
}


/*this program deletes all the nodes in the Linked List, after executing this program Linked List becomes empty */

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
template<class T>
class sll;
template<class T>
class node
{
 private:
  T data;
  node<T>* link;
 friend class sll<T>;
};
template <class T>
class sll
{
 private:
  node<T> * first;
 public:
 //Mem.Fun declarations
  sll();
  ~sll();
  int isempty();
  void display();
  void append(node<T> *k);
  void create();
  void erase();

};
//Member Functions defination
template<class T>
sll<T>::sll()
{
 first=NULL;//first points to no where,it is an empty node
}
template<class T>
int sll<T>::isempty()
{
 return(first==NULL);//return true when linked list is empty and false otherwise
}
template<class T>
void sll<T>::display()
{
 node<T>* p;//p is pointer to a node
 if(isempty())
  cout<<"Linked List is empty\n";
 else
 {
  cout<<"Linked list is as follows\n";
  p=first;
  while(p!=NULL)
  {
   cout<<p->data<<"\t"<<p->link<<"\n";
   p=p->link;
  }
 }//end of else
}//end of display()
template<class T>
void sll<T>::append(node<T> *k)
{
 node<T> *last;
 k->link=NULL;
 if(isempty())
  first=k;
 else
 {
  last=first;
  while(last->link!=NULL)//keep moving last pointer until last node is reached
  {
   last=last->link;
  }
  last->link=k;//attach last node and new node k
 }
}
template <class T>
void sll<T>::create()
{
 T x;
 node<T> *k;
 first=NULL;
 cout<<"enter values terminated by -1 or !\n";
 cin>>x;
 while(x!=-1&&x!='!')
 {
  k=new node<T>;
  k->data=x;
  append(k);
  cin>>x;
 }
}//end of create()
//c.c
template<class T>
sll<T>::sll(sll<T> &a)
{
 node<T> *p,*k;
 first=NULL;
 p=a.first;
 while(p!=NULL)
 {
  k=new node<T>;
  k->data=p->data;
  append(k);
  p=p->link;
 }
}
 //erase function defination
template<class T>
void sll<T>::erase()
{
 node<T> *p;
 while(!isempty())
 {
  p=first;
  first=first->link;
  delete p;
 }
}
//defining the destructor of sll
template<class T>
sll<T>::~sll()
{
 erase();
}
 

void main()
{
 sll<int> a;//creating object a, d.c is called

  a.create();
  cout<<"before erase function\n";
     a.display();
 a.erase(); //calling erase() function
 cout<<"after erase function\n";
   a.display();
 getch();
}



No comments:

Post a Comment