Friday, 11 May 2012

Joining Two Linked Lists in C



#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#define newnode (struct a*) malloc(sizeof(struct a))


struct a
{
int data;
struct a *next;
};


struct a *create();
struct a *join(struct a *f1, struct a *f2);
void main()
{
struct a *f1,*f2,*f3;
int len,reply;
f1 = f2 = NULL;
clrscr();
printf("\nEnter first list\n");
f1 = create();
printf("\nEnter second list\n");
f2 = create();
printf("\n First list is\n");
display(f1);
printf("\n Second list is\n");
display(f2);
f3 = join(f1,f2);
printf("\nThe resultant list is \n");
display(f3);
}
struct a *create()
{
struct a *f,*c,*p;
int info;
f = NULL;
printf("\n Enter data ( use 0 to exit ) : ");
scanf("%d",&info);
while( info != 0 )
{
c = newnode;
if( c == NULL)
{
printf("\n Insuf. mem. ");
exit(0);
}
c->data = info;
c->next = NULL;
if( f== NULL)
f = c;
else
p->next = c;
p = c;
printf("\n Enter data ( use 0 to exit ) : ");
scanf("%d",&info);

return(f);



display( struct a *f)
{
struct a *t;

if( f == NULL)
{
printf("List is empty");
return;
}
t = f;
while ( t != NULL)
{
printf("%4d",t->data);
t = t->next;
}
return;
}


struct a *join(struct a *f1, struct a *f2)
{
int reply;
struct a *t1,*t2;

if( f1 == NULL && f2 == NULL)
return(NULL);
else
if( f1 != NULL && f2 == NULL)
return(f1);
else
if( f1 == NULL && f2 != NULL)
return(f2);
else
{
t1 = f1;
while ( t1->next != NULL )
{
t1 = t1->next;
}
t1->next = f2;
return(f1);
}
}

No comments:

Post a Comment