Union of two linked list

Can anybody tell me the logic of union of two linked list?
In set theory the union of two sets A and B is the set C that contains all the elements in A and B. An elements is either in the set or it is not. Asking how many times an element is contained in a set doesn't really make sense. The elements in a set does not have any particular order.

It is not clear what a union of linked list means.
1
2
3
4
5
6
7
8
9
10
11
12
std::list<int> A = {1, 2, 3};
std::list<int> B = {2, 0, 10};

// Create the list C and insert all the elements in both lists.
std::list<int> C;
C.insert(A.begin(), A.end());
C.insert(B.begin(), B.end());
// Is this what they mean? It could be, but notice that the list C contains duplicates. 

// If we want to remove the duplicates we could do that.
C.sort();
C.erase(std::unique(C.begin(), C.end()), C.end());
Last edited on
1
2
3
4
5
\[
  C = A \cup B \iff
    \forall x \in C \quad
      x \in A \vee x \in B
\]


I guess I should have updated the page first.
@OP: you don't interset/union/difference list. You do that operations to sets.
How your set is implemented is irrelevant (althought some implementations permit optimizations).
So make your ADT set and implement this operations:
_ insert
_ remove
_ ¿member?

_ iterate (because if you don't have access to the elements, a container is useless)

Then using those operations, implement whatever you need to.
Last edited on
By instance
With sorted lists you can achieve O(n) simply providing a hint to the ¿member? method.
With unsorted lists you can achieve O(1) (destructive). You only need to make remove() handle repeated elements.
i don't want to use any method as you said C.sort()...i want to do it is using code....
*sigh*
1
2
3
4
for( x: traverse(A) )
  insert( C, x );
for( x: traverse(B) )
  insert( C, x );
@ne555: what if you don't have c++11?
¿eh? It was pseudocode
Topic archived. No new replies allowed.