21921

# How to get the common elements of the two sets in a Linked List?

I have got 2 linkedlist, I want to compare both lists and print every common element that appears in both list. tried everything can't get it to work.

```struct Node *calcIntersection(struct Node *headA, struct Node *headB) { struct Node * link1 = headA; struct Node * link2 = headB; while(link1 != NULL) { if (link2->value == link2->value) { printf("%d", link1->value); } link1 = link1 -> pNext; } return link1; } ```

You are close, in reality your method should look like this:

```struct Node *calcIntersection(struct Node *headA, struct Node *headB) { struct Node *link1 = headA; while(link1 != NULL) { struct Node *link2 = headB; while (link2 != NULL) { if (link1->value == link2->value) { printf("%d", link1->value); } link2 = link2->pNext; } link1 = link1->pNext; } return link1; } ```

I'm not quite sure what you are returning there, but in most situations you will be returning NULL, I'm not quite sure if that's what you want however.

OK.. This looks like homework.. so I will point out a few things that are pretty obvious in the code above

1) The condition you are checking for (link2->value == link2->value) is probably a typo. You might have meant link2->value == link1->value. 2) You are iterating over every element in list 1 but NOT in list 2. So you are checking only if the first element in list 2 is found in list 1.

I think this is sufficient.. for now.. :)

```if (link2->value == link2->value) ```
```if (link1->value == link2->value) ```