#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
void print(node *t)
{
if(t!=NULL)
{
cout<<t->data<<" ";
print(t->next);
}
}
node * create(int a)
{
node *t=new node;
t->data=a;
t->next=NULL;
return t;
}
node * swap(node *t,int a,int b)
{
if(t==NULL ||t->next==NULL)
return t;
node *x,*y;
x=t;
while(x->data!=a&&x)
x=x->next;
y=t;
while(y->data!=b)
y=y->next;
node *m=y->next;
node *t1=t;
while(t1->next!=x&&t1->next)
t1=t1->next;
t1->next=y;
y->next=x->next;
node *y1=y;
while(y->next!=y1)
y=y->next;
y->next=x;
x->next=m;
return t;
}
int main()
{
node *t=NULL;
t=create(4);
t->next=create(2);
t->next->next=create(11);
t->next->next->next=create(43);
t->next->next->next->next=create(13);
t->next->next->next->next->next=create(45);
print(t);
cout<<endl;
t=swap(t,2,13);
print(t);
return 0;
}
using namespace std;
struct node
{
int data;
node *next;
};
void print(node *t)
{
if(t!=NULL)
{
cout<<t->data<<" ";
print(t->next);
}
}
node * create(int a)
{
node *t=new node;
t->data=a;
t->next=NULL;
return t;
}
node * swap(node *t,int a,int b)
{
if(t==NULL ||t->next==NULL)
return t;
node *x,*y;
x=t;
while(x->data!=a&&x)
x=x->next;
y=t;
while(y->data!=b)
y=y->next;
node *m=y->next;
node *t1=t;
while(t1->next!=x&&t1->next)
t1=t1->next;
t1->next=y;
y->next=x->next;
node *y1=y;
while(y->next!=y1)
y=y->next;
y->next=x;
x->next=m;
return t;
}
int main()
{
node *t=NULL;
t=create(4);
t->next=create(2);
t->next->next=create(11);
t->next->next->next=create(43);
t->next->next->next->next=create(13);
t->next->next->next->next->next=create(45);
print(t);
cout<<endl;
t=swap(t,2,13);
print(t);
return 0;
}
No comments:
Post a Comment