Tuesday, September 21, 2010

Sample code for Linked list in c++

============================================================================

#include




using namespace std;



class linklist

{

private:



struct node

{

int data;

node *link;

}*p;



public:



linklist();



void addfirst( int num );

void addafter( int c, int num );

void delete( int num );

void display();

int count();

~linklist();

};



linklist::linklist()

{

p=NULL;

}

void linklist::addfirst(int num)

{

node *q;



q = new node;

q->data = num;

q->link = p;

p = q;

}



void linklist::addafter( int c, int num)

{

node *q,*t;

int i;

for(i=0,q=p;i

{

q = q->link;

if( q == NULL )

{

cout<<"\nThere are less than "<

return;

}

}



t = new node;

t->data = num;

t->link = q->link;

q->link = t;

}



void linklist::delete( int num )

{

node *q,*r;

q = p;

if( q->data == num )

{

p = q->link;

delete q;

return;

}



r = q;

while( q!=NULL )

{

if( q->data == num )

{

r->link = q->link;

delete q;

return;

}



r = q;

q = q->link;

}

cout<<"\nElement "<

}



void linklist::display()

{

node *q;

cout<



for( q = p ; q != NULL ; q = q->link )

cout<data;



}



int linklist::count()

{

node *q;

int c=0;

for( q=p ; q != NULL ; q = q->link )

c++;



return c;

}



linklist::~linklist()

{

node *q;

if( p == NULL )

return;



while( p != NULL )

{

q = p->link;

delete p;

p = q;

}

}



int main()

{

linklist ll;

cout<<"No. of elements = "<

ll.addfirst(2);

ll.addfirst(1);



ll.addafter(3,333);

ll.addafter(6,666);



ll.display();

cout<<"\nNo. of elements = "<



ll.delete(333);

ll.delete(12);

ll.delete(98);

cout<<"\nNo. of elements = "<

return 0;

}


============================================================================