www.cprograms.in
Home > Link list

Join two doubly circular linked list and print it.

     This program shows how to create doubly circular linked list using dynamic memory allocation and pointers.If both the link lists are NULL then NULL is returned.If either of the two link list is NULL then the NULL link list is neglected and the other link list is returned as final output.If both the link list are not NULL then the pointer moves to the end of first link list.Then the second link list acts as next of first link list.
  
#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_list();
struct node *join_list(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_list();
	printf("\nEnter second list\n");
	f2 = create_list();
	printf("\n First list is\n");
	print_list(f1);
	printf("\n Second list is\n");
	print_list(f2);
	f3 = join_list(f1,f2);
	printf("\nThe resultant list is \n");
	print_list(f3);
} // main

struct node *create_list()
{
	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);
	} //while
	f->prev = c;
	c->next= f;
	return(f);
} // create list

print_list( 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_list(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);
	}
}