Friday, 11 May 2012

Join Doubly Circular Linked Lists in C


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


struct node
{
int data;
struct node *next;
struct node *prev;
};


struct node *create();
struct node *join(struct node *f1, struct node *f2);


void main()
{
struct node *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 node *create()
{
struct node *f,*c,*p;
int tdata;
f = NULL;
printf("\n Enter data ( use 0 to exit ) : ");
scanf("%d",&tdata);
while( tdata != 0 )
{
c = newnode;
if( c == NULL)
{
printf("\n Insuf. mem. ");
exit(0);
}
c->data = tdata;
c->next = NULL;
c->prev = NULL;
if( f== NULL)
f = c;
else
{
p->next = c;
c->prev = p;
}
p = c;
printf("\n Enter data ( use 0 to exit ) : ");
scanf("%d",&tdata);

f->prev = c;
c->next= f;
return(f);



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

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


struct node *join(struct node *f1, struct node *f2)
{
int reply;
struct node *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->prev;
t2 = f2->prev;
t1->next = f2;
f2->prev = t1;
f1->prev = t2;
t2->next = f1;
return(f1);
}
}

No comments:

Post a Comment