Thursday 7 November 2013

c program for concatenation of two singly linked lists

#include<stdio.h>
#include<stdlib.h>

struct node
{
int info;
struct node *link;
};
struct node *create_list(struct node *);
struct node *concat( struct node *start1,struct node *start2);
struct node *ins(struct node *start,int data);
void display(struct node *start);

void main()
{
struct node *start1=NULL,*start2=NULL;
start1=create_list(start1);
start2=create_list(start2);
printf("First list is  : ");
display(start1);
printf("Second list is  : ");
display(start2);
start1=concat(start1, start2);
printf("Concatenated list is  : ");
display(start1);
}

struct node *concat( struct node *start1,struct node *start2)
{
struct node *ptr;
if(start1==NULL)
{
 start1=start2;
 return start1;
}
if(start2==NULL)
 return start1;
ptr=start1;
while(ptr->link!=NULL)
 ptr=ptr->link;
ptr->link=start2;
return start1;
}
struct node *create_list(struct node *start)
{
int i,n,data;
printf("Enter the number of nodes : ");
scanf("%d",&n);
start=NULL;
if(n==0)
 return start;

for(i=1;i<=n;i++)
{
 printf("Enter the element to be inserted : ");
 scanf("%d",&data);
 start=ins(start,data);
}
return start;
}

void display(struct node *start)
{
struct node *p;
if(start==NULL)
{
 printf("List is empty\n");
 return;
}
p=start;
while(p!=NULL)
{
 printf("%d ", p->info);
 p=p->link;
}
printf("\n");
}
struct node *ins(struct node *start,int data)
{
 struct node *temp,*p;
 temp=(struct node *)malloc(sizeof(struct node));
 temp->info=data;
if(start==NULL)
{
 temp->link=start;
 start=temp;
}
else
{
p=start;
while(p->link!=NULL)
{
p=p->link;
}
temp->link=p->link;
p->link=temp;
}
return start;
}

No comments:

Post a Comment