Thursday, October 8, 2015

Merge a linked list into another linked list at alternate positions

#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 * altswap(node *t,node *l)
{
if(t==NULL )return l;
if(l==NULL) return t;
node *x,*y;
x=t;
while(t&&l){
y=t->next;
t->next=l;
l=y;
t=t->next;
}

return x;
}
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);
node *l=NULL;
l=create(1);
l->next=create(3);
l->next->next=create(12);
l->next->next->next=create(63);
l->next->next->next->next=create(153);
l->next->next->next->next->next=create(145);

print(t);
cout<<endl;
print(l);
cout<<endl;
t=altswap(t,l);
print(t);
return 0;
}

No comments:

Post a Comment

Contributors

Translate