My photo
Bangalore, Karnataka, India
Extending one hand to help someone has more value rather than joining two hands for prayer

Archives

program to search a node by value and replace it with the next node

Tuesday, September 1, 2009

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
struct node
{ int info;
  node *link;
};
class linklist
{ node *start;
  public:
  linklist()
  { start=NULL; }
  void insert(int);
  void swap(int);
  void show();
 };

 void linklist::insert(int a)
 {  node *p=new node;
    p->info=a;
    if(start==NULL)
    { start=p;
      p->link=NULL;
    }
     else
     {  node *q=start;
    while(q->link!=NULL)
    { q=q->link;
    }
    q->link=p;
    p->link=NULL;
     }

  }

  void linklist::swap(int a)
  {
     node *p1,*p2,*p3;
     p1=start;
     p2=p1->link;
     p3=p2->link;

     if(p1->info==a)
     {  start=p2;
    p2->link=p1;
    p1->link=p3;
    return;
     }

     while(p2!=NULL)
     {  if(p2->info==a)
    {  p1->link=p2->link;
       p2->link=p3->link;
       p3->link=p2;
       return;
    }
    p1=p1->link;
    p2=p2->link;
    p3=p3->link;
     }
     cout<<"there is no node at this value"<<endl;
  }








   void linklist::show()
   {
      node *p=start;
      while(p!=NULL)
      {   cout<<p->info<<endl;
      p=p->link;
      }
    }
  void main()
  {
     clrscr();
     int p;
     linklist l1;
     l1.insert(10);
     l1.insert(20);
     l1.insert(30);
     l1.insert(40);
     l1.insert(50);
     l1.show();
     getch();
     cout<<"\nenter the value which u want to swap with next node: ";
     cin>>p;
     l1.swap(p);
     l1.show();
     getch();
     cout<<"\nenter the value again: ";
     cin>>p;
     l1.swap(p);
     l1.show();
     getch();
   }

0 comments: