【HBU】1-7 两个有序链表序列的交集 (20分)

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。

输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。

输出格式:
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。

输入样例:

1 2 5 -1
2 4 5 8 10 -1

输出样例:

2 5

使用set中的求解交集的函数,注意添加算法头文件,当然也可以自己写交集函数
#include <iostream>
#include <vector>
#include <set> 
#include <algorithm>
using namespace std;

int main(){
    
    
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	vector<int> v1,v2,v3;
	int num;
	while(true){
    
    
		cin >> num;
		if(num==-1)
			break;
		v1.push_back(num);
	}
	while(true){
    
    
		cin >> num;
		if(num==-1)
			break;
		v2.push_back(num);
	}
	set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),inserter(v3,v3.begin()));
	if(v3.empty()){
    
    
		cout << "NULL";
		return 0;
	}
	for(auto it = v3.begin();it!=v3.end();it++){
    
    
		if(it==v3.begin())
			cout << *it;
		else
			cout << " " << *it;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45845039/article/details/108631524