题目如下:
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL
。
输入样例:
1 2 5 -1
2 4 5 8 10 -1
输出样例:
2 5
1.用multiset而不是set;2.用迭代器删除而不是值删除;3.未规定整数范围,用long。代码如下:
#include <iostream>
#include <set>
using namespace std;
multiset<long>st;
int main()
{
long x,cnt=0;
while(scanf("%ld",&x)!=EOF,x!=-1)
{
st.insert(x);
}
while(scanf("%ld",&x)!=EOF,x!=-1)
{
auto it=st.find(x);
if(st.end()!=it)
{
if(cnt++) printf(" ");
printf("%d",x);
st.erase(it);
}
}
if(cnt==0) cout<<"NULL";
cout<<endl;
return 0;
}