# Union and Intersection of two Linked Lists

Given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. Order of elments in output lists doesnâ€™t matter.

Following are simple algorithms to get union and intersection lists respectively.

Intersection (list1, list2)
Initialize result list as NULL. Traverse list1 and look for its each element in list2, if the element is present in list2, then add the element to result.

Union (list1, list2):
Initialize result list as NULL. Traverse list1 and add all of its elements to the result.
Traverse list2. If an element of list2 is already present in result then do not insert it to result, otherwise insert.

This method assumes that there are no duplicates in the given lists.

```/* A utility function to insert a node */
void insert(struct node** head_ref, int new_value);

/* A utility function to check if given value is present in a list */

bool isPresent (struct node *head, int value)
{
while (t != NULL)
{
if (t->value == value)
return 1;
t = t->next;
}
return 0;
}

{
struct node *result = NULL;

// Insert all elements of list1 to the result list
while (t1 != NULL)
{
insert(&result, t1->value);
t1 = t1->next;
}

// Insert those elements of list2 which are not
// present in result list
while (t2 != NULL)
{
if (!isPresent(result, t2->value))
insert(&result, t2->value);
t2 = t2->next;
}

return result;
}

/* Function to get intersection of two linked lists
{
struct node *result = NULL;

// Traverse list1 and search each element of it in
// list2. If the element is present in list 2, then
// insert the element to result
while (t1 != NULL)
{
insert (&result, t1->value);
t1 = t1->next;
}

return result;
}

/* A utility function to insert a node at the begining of a linked list*/
void insert (struct node** head_ref, int new_value)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));

/* put in the value */
new_node->value = new_value;

/* link the old list off the new node */