Saturday 16 September 2017

Swapping of two nodes without changing its value in Linklist in C++/C

#include<bits/stdc++.h>
#include<conio.h>
using namespace std;
struct node
{
int info;
node *link;
};
void insert(node **start,int num)
{
node *temp=new node;
temp->info=num;
temp->link=(*start);
*(start)=temp;
}
void swap1(node **start,int x,int y)
{
node *currx;
node *prevx=NULL;

currx=(*start);

while(currx&&currx->info!=x)
{
prevx=currx;
currx=currx->link;
}
node *curry=(*start);
node *prevy=NULL;

while(curry&&curry->info!=y)
{
prevy=curry;
curry=curry->link;
}

if (currx == NULL || curry == NULL)
       return;

  
  if (prevx != NULL)
      prevx->link = curry,cout<<"X";
  else
     *start = curry;  

  
  if (prevy != NULL)
       prevy->link = currx,cout<<"Y";
    else 
      *start = currx;
     swap(currx->link,curry->link);





}

void show(node *start)
{
node *p=start;
if(p==NULL)
cout<<"List Is Empty";

while(p!=NULL)
{
cout<<p->info<<" ";
p=p->link;
}
}

main()
{
struct node *start=NULL;

int num,x,y;
insert(&start,1);
insert(&start,5);
insert(&start,3);
insert(&start,4);
insert(&start,2);
cout<<"Enter Number To Swap:";
cin>>x>>y;
swap1(&start,x,y);
cout<<"After Swapping Address Values Are....:\n";
show(start);

}


No comments:

Post a Comment

Amazon1Ads