#include <iostream>
#include <list>
using namespace std;
void printlist (const list<int> &s);
list<int> jiao_ji (list<int> L1,list <int>L2);
list<int> bing_ji (list<int> L1,list <int>L2);
int main()
{
int num_1[11]={1,2,3,5,7,9,10,12,17,20,23}; //int num_1[11]={1,2,3,5,7,9,10,12,17,20,23};
int num_2[8] = {0,2,3,5,9,10,13,24}; //int num_2[8] = {0,2,3,5,9,10,13,22};
list <int >L1(num_1,num_1+11);
list<int> L2(num_2,num_2+8);
printlist(L1);
cout<<endl;
printlist(L2);
cout<<endl;
list <int >jiao;
list <int >bing;
jiao=jiao_ji(L1,L2);
cout<<"L1和L2的交集是:";
printlist(jiao);
cout<<endl;
bing=bing_ji(L1,L2);
cout<<"L1和L2的并集是:";
printlist(bing);
cout<<endl;
return 0;
}
//求交集
list<int> jiao_ji (list<int> L1,list <int>L2)//存在一个问题,当L2先为空或者二者同时为空是就出现问题,当L1先为空时则没有问题???
{
list <int >temp;
while(!L1.empty ()&&!L2.empty ())
{
int k=L1.front ();
if (k<L2.front ())
L1.pop_front ();
else
{
while (k>=L2.front() &&!L2.empty ())
{
if (k==L2.front ()){
temp.push_back (k);
L1.pop_front ();
L2.pop_front ();
}
else
L2.pop_front ();
}
}
}
return temp;
}
//求并集
list<int> bing_ji (list<int> L1,list <int>L2)
{
list <int> temp;
while (!L1.empty ()&&!L2.empty ())
{
int k=L1.front ();
if (k<L2.front ())
{
temp.push_back (k);
L1.pop_front ();
}
else if (k==L2.front ())
{
temp.push_back (k);
L1.pop_front ();
L2.pop_front ();
}
else
{
while (k>L2.front ()&&!L2.empty ())
{
temp.push_back (L2.front ());
L2.pop_front ();
}
}
}
if (L1.empty ())
while (!L2.empty ()){
temp.push_back (L2.front ());
L2.pop_front ();
}
if (L2.empty ())
while (!L1.empty ()){
temp.push_back (L1.front ());
L1.pop_front ();
}
return temp;
}
void printlist (const list<int> &s)
{
list<int>::const_iterator it=s.begin ();
while (it!=s.end()){
cout<<*it++<<' ';
}
}