链表求交集

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Fiverya/article/details/88814125

已知两个单链表 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;
}

猜你喜欢

转载自blog.csdn.net/Fiverya/article/details/88814125