两个有序链表序列的交集(20 分)

本文介绍了一种求解两个非降序链表交集的方法,通过STL set_intersection函数直接求解,并提供了两种实现方案:一种使用STL容器,另一种采用链表实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两个有序链表序列的交集(20 分)

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

输入格式:

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

输出格式:

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

输入样例:

1 2 5 -1
2 4 5 8 10 -1
输出样例:

2 5

思路

使用stl的set_intersection直接求交集。注意这个方法是有返回值的,利用它返回的这个迭代器将它以及它之后的迭代器都删除。

源码1

/*
	Name: 7-3 两个有序链表序列的交集(20 分)
	Author: shou1651312
	Date: 2017年9月18日 01:21:42
	Description:数据结构实验1-2

*/
#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<numeric>
using namespace::std;
int main()		//version1 stl 20/20
{
	vector<int> V1;
	vector<int> V2;
	while(true)
	{
		int input;
		scanf("%d",&input);
		if(input!=-1)
			V1.push_back(input);
		else
			break;
	}
	while(true)
	{
		int input;
		scanf("%d",&input);
		if(input!=-1)
			V2.push_back(input);
		else
			break;
	}
	int l1=V1.size(),l2=V2.size();
	vector<int> V3(max(l1,l2));
	auto it_=set_intersection(V1.begin(),V1.end(),V2.begin(),V2.end(),V3.begin());
	V3.erase(it_,V3.end());
	if(V3.size()==0)
		printf("NULL");
	else
	{
		auto it=V3.begin();
		printf("%d",*it);
		it++;
		for(; it!=V3.end(); it++)
			printf(" %d",*it);
	}
	return 0;
}

源码2

#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<numeric>
using namespace::std;
typedef struct Node* List;		//version2 chainlist 20/20
struct Node
{
	int Data;
	struct Node*Next;
};
List Search(List L1,List L2,List L3);
List init();
void Insert(List L,int t);
int main()
{
	List L1,L2,L3;
	int t;
	L1=init();
	L2=init();
	L3=init();
	while(1)
	{
		scanf("%d",&t);
		if(t==-1)
			break;
		else
			Insert(L1,t);
	}
	while(1)
	{
		scanf("%d",&t);
		if(t==-1)
			break;
		else
			Insert(L2,t);
	}
	if((!L1)||(!L1->Next)||(!L2)||(!L2->Next))
	{
		printf("NULL");
		return 0;
	}
	L3=Search(L1,L2,L3);
	if((!L3)||(!L3->Next))
	{
		printf("NULL");
		return 0;
	}
	for(L3=L3->Next; L3->Next!=NULL; L3=L3->Next)
		printf("%d ",L3->Data);
	printf("%d",L3->Data);
	return 0;
}
List init()
{
	List L;
	L=(List)malloc(sizeof(struct Node));
	if(!L)return NULL;
	L->Next=NULL;
	return L;
}
void Insert(List L,int t)
{
	List p=(List)malloc(sizeof(struct Node));
	if(!p)
		return ;
	p->Data=t;
	p->Next=L->Next;
	L->Next=p;
	return ;
}
List Search(List L1,List L2,List L3)
{
	List p,q;
	p=L1->Next;
	q=L2->Next;
	while((p!=NULL)&&(q!=NULL))
	{
		if(p->Data<q->Data)
			q=q->Next;
		else if(p->Data>q->Data)
			p=p->Next;
		else
		{
			Insert(L3,p->Data);
			p=p->Next;
			q=q->Next;
		}
	}
	return L3;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值