u

Thursday 7 June 2012

C++ Program to implement Linked List

C++ Program to implement Linked List


#include <iostream.h>
#include <conio.h>
struct node
{
   node* ptr;
   int data;
};

class list
{
   node* lastptr;

    public:
   list();
   ~list();
   void add(int);
   void remove(int);
   void display();
   node* searchnode(int);
   void releasenode();   
};

list::list()
{
   lastptr='\0';
}

list::~list()
{
   while (lastptr)
   {
      node* thisptr=lastptr;
      lastptr=lastptr->ptr;
      delete thisptr;
   }
}

void list::add(int value)
{
   node* thisptr=new(node);
   thisptr->data=value;
   thisptr->ptr=lastptr;
   lastptr=thisptr;
}

node* list::searchnode(int value)
{
   node* thisptr=lastptr;
   while (thisptr)
   {
      if (thisptr->data==value)
         break;
      thisptr=thisptr->ptr;
   }
   return thisptr;
}

void list::remove(int value)
{
   node* thisptr=searchnode(value);

   if (!thisptr) return;
   while (thisptr->ptr)
   {
      node* pptr=thisptr->ptr;
      thisptr->data=pptr->data;
      thisptr=thisptr->ptr;
   }
   releasenode();
}

void list::releasenode()
{
   node* thisptr=lastptr;
   node* previousptr;
   while (thisptr->ptr)
   {
      previousptr=thisptr;
      thisptr=thisptr->ptr;
   }
   if (thisptr==lastptr) lastptr='\0';
   else previousptr->ptr='\0';
   delete thisptr;
}

void list::display()
{
   node* thisptr=lastptr;

   //Loop until this pointer equal to NULL.
   while (thisptr)
   {
      cout<<"Data : "<<thisptr->data<<"\n";
      cout<<"Address : "<<thisptr->ptr<<"\n";
      thisptr=thisptr->ptr;
   }
}

void main()
{
   list linklist;
   
   //add number(1 until 7) into link list.
   linklist.add(1);      
   linklist.add(2);
   linklist.add(3);
   linklist.add(4);
   linklist.add(5);
   linklist.add(6);
   linklist.add(7);
       getch();
   //remove number 4 from the list.
   linklist.remove(4);

   //display the number in descending order.
   linklist.display();
   cout<<endl;
   cout<<"Press any key to continue"<<endl;
   getch();
}

0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More