已知两个单链表 LA 和 LB 分别表示两个集合,其元素递增排序,设计算法求出 LA 和 LB 的交集 C ,要求 C 同样以元素递增的单链表形式存储。
#include<iostream>
#include<list>
using namespace std;
int main()
{
list<int> LA,LB,LC;
list<int>::iterator j,m,n;
int x;
do
{ cin>>x;
LA.push_back(x);
} while(getchar()!='\n');
do
{ cin>>x;
LB.push_back(x);
}while(getchar()!='\n');
for (j = LA.begin(),m= LB.begin(); j!= LA.end()&&m!= LB.end(); )
if(*j==*m) {LC.push_back(*j);j++;m++;}
else *j>*m?m++:j++;
if(LC.empty()) cout<<"没有交集";
else
for (n = LC.begin(); n!= LC.end(); ++n)
cout<<*n <<" ";
cout<<endl;
return 0;
}