题目:
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
输入样例:
1 2 5 -1
2 4 5 8 10 -1
输出样例:
2 5
代码:
#include <iostream>
using namespace std;
// 1 定义链表
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*Linklist;
//2 后插法创建链表
void Create(Linklist &L)
{
L=new LNode;
L->next=NULL;
Linklist p;
Linklist s=L;
int a;
while(cin>>a&&a!=-1)
{
p=new LNode;
p->data=a;
p->next=NULL;
s->next=p;
s=p;
}
}
// 3 求交集
void intersection(Linklist &s1,Linklist &s2,Linklist &s3)
{
s3=new LNode;
s3->next=NULL;
Linklist i=s1->next;
Linklist j=s2->next;
Linklist k=s3;
while(i&&j)
{
if(i->data>j->data) j=j->next;
else if(i->data<j->data) i=i->next;
// s3 用来存放交集
else
{
Linklist p=new LNode;
p->next=NULL;
p->data=i->data;
k->next=p;
k=p;
i=i->next;
j=j->next;
}
}
}
int main()
{
Linklist s1,s2,s3;
Create(s1);
Create(s2);
intersection(s1,s2,s3);
Linklist p=s3->next;
if(p==NULL) cout<<"NULL"<<endl;
else
{
int flag=0;
while(p)
{
if(flag) cout<<" ";// 保证末尾没有多余的空格
cout<<p->data;
p=p->next;
flag++;
}
}
}