两个有序链表序列的交集(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;
}