Program for union of two linked lists

Union of two linked list will give the distinct elements of both the linked list.

List 1 : 4->8->9->30->5
List 2 : 6->4->9->32->7
Union : 4->8->9->30->5->6->32->7

The logic for program of union of two linked list is very simple.Take the resultant linked list and initialize it to NULL.Now traverse list 1 till the null and insert all the values in resultant linked list.Now take list 2 and check whether the value of list 2 is already present in resultant linked list.If the value is not present in the linked list then insert it otherwise move forward without inserting.

Program :

struct node
{
int data;
node* next;
}
void insert(node** head,int value)
{
node* temp;
temp=(node*)malloc(sizeof(node));
temp->data=value;
temp->next=head;
head=temp;
}

bool present(node* head,int data)
{
node* temp;
temp=(node*)malloc(sizeof(node));
while(temp!=NULL)
{
if(temp->data==data)
return 1;
temp=temp->next;
}
return 0;
}

struct node *union(node* head1,node* head2)
{
struct node* resultant=NULL;
node*t1=(node*)malloc(sizeof(node));
node*t2=(node*)malloc(sizeof(node));
t1=head1;
t2=head2;
while(t1!=NULL)
{
insert(&resultant,t1->data)
t1=t1->next;
}
while(t2!=NULL)
{
if(!present(resultant,t2->data))
insert(&resultant,t2->data);
t2=t2->next;
}
return resultant;
}

Comments

Popular posts from this blog

Tricky Questions or Puzzles in C

Program to uncompress a string ie a2b3c4 to aabbbcccc

Programs and Puzzles in technical interviews i faced