Showing posts with label node swap in linked list. Show all posts
Showing posts with label node swap in linked list. Show all posts

Thursday, October 8, 2015

Swap nodes in a linked list without swapping data

#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;
}

Contributors

Translate