Tuesday, October 1, 2013

merge two linked list

#include<stdio.h>
#include<conio.h>
#include<malloc.h>

typedef struct node
{
int info;
struct node *next;
}node;

node *start1=NULL,*start2=NULL,*start3=NULL,*cur;

void make_node(int x)
{
cur=(node*)malloc(sizeof(node)) ;
cur->info=x;
cur->next=NULL;
}
void create_list(node **first, int x)
{
node *temp;
make_node(x);
if(*first==NULL)
*first=cur;
else
{
temp=*first;
while(temp->next!=NULL)
temp=temp->next;
temp->next=cur;
}
}
void traverse(node *first)
{
while(first!=NULL)
{
printf("\t%d",first->info);
first=first->next;
}
}
void sort(node *first)
{
node *n;
int temp;
for(;first!=NULL;first=first->next)
{
for(n=first->next;n!=NULL;n=n->next)
{
if(first->info > n->info)
{
temp=first->info;
first->info=n->info;
n->info=temp;
}
}
}
}

void merge()
{
node *m,*n;
m=start1;
n=start2;
while(m!=NULL && n!=NULL)
{
if(m->info < n->info)
{
create_list(&start3,m->info);
m=m->next;
}
else
{
create_list(&start3,n->info);
n=n->next;
}
}
while(m!=NULL)
{
create_list(&start3,m->info);
m=m->next;
}
while(n!=NULL)
{
create_list(&start3,n->info);
n=n->next;
}
}

int main()
{
int n;
char ch;
printf("\nCreate the first list :\n");
do
{
printf("\nEnter the info :");
scanf("%d",&n);
create_list(&start1,n);
printf("\nWant to continue?[y/n] :");
ch=getche();
}while(toupper(ch)=='Y');
printf("\nCreate the second list :\n");
do
{
printf("\nEnter the info :");
scanf("%d",&n);
create_list(&start2,n);
printf("\nWant to continue?[y/n] :");
ch=getche();
}while(toupper(ch)=='Y');
printf("\n\nFirst List :");
traverse(start1);
printf("\n\nSecond List :");
traverse(start2);
sort(start1);
sort(start2);
merge();
printf("\n\nMerged List :");
traverse(start3);
getch();
return 0;
}

1 comment:

Anonymous said...

thanks