Consider following example :
l1, l2, common, unique are 4 linked lists. Nodes in l1 and l2 are in sorted order. common and unique and empty linked lists.
l1 = 1->3->5->8
l2 = 3->4->8->9
common = null
unique = null
Using iterative method, I figured out that I can easily find common and unique elements as follows:
- Traverse l1 and l2
- If l1->data < l2->data, add a new node with l1->data to unique and increment pointer for l1
- If l1->data > l2->data, add a new node with l2->data to unique and increment pointer for l2
- If l1->data == l2->data, add a new node with l2->data to common and increment pointers for both l1 and l2.
I can't figure out the recursive approach for this problem.
Update:
Both the linked lists can be thought of as set of elements sorted in ascending order. A number can occur at most twice. (Either in both of them, or in exactly one of them, or none of them).