7-3 两个有序链表序列的交集 (20 分)
时间限制: 1000 ms 内存限制: 64 MB 代码长度限制: 16 KB
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL
。
输入样例:
1 2 5 -1
2 4 5 8 10 -1
输出样例:
2 5
#include<stdio.h>
#include<stdlib.h>
typedef struct Node* List;
struct Node{
int Data;
struct Node*Next;
};
List creat(){
List S;
S=(List)malloc(sizeof(struct Node));
if(!S)return NULL;
S->Next=NULL;
return S;
}
void Insert(List S,int t){
List p=(List)malloc(sizeof(struct Node));
if(!p)return ;
p->Data=t;
p->Next=S->Next;
S->Next=p;
return ;
}
void Find(List S1,List S2,List S3){
List p,q;
p=S1->Next;
q=S2->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(S3,p->Data);
p=p->Next;
q=q->Next;
}
}
return S3;
}
int main(){
List S1,S2,S3;
int t;
S1=creat();
S2=creat();
S3=creat();
while(1){
scanf("%d",&t);
if(t==-1){
break;
}
else{
Insert(S1,t);
}
}
while(1){
scanf("%d",&t);
if(t==-1){
break;
}
else{
Insert(S2,t);
}
}
if((!S1)||(!S1->Next)||(!S2)||(!S2->Next)){
printf("NULL");
return 0;
}
Find(S1,S2,S3);
if((!S3)||(!S3->Next)){
printf("NULL");
return 0;
}
for(S3=S3->Next;S3->Next!=NULL;S3=S3->Next){
printf("%d ",S3->Data);
}
printf("%d",S3->Data);
return 0;
}