已知兩個非降序鏈表序列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;
int a[9999999];
int b[9999999];
int c[9999999];
int main(){
int ai=0,bi=0,ci=0;
cin>>a[ai];
while(a[ai]!=-1)cin>>a[++ai];
cin>>b[bi];
int si=0;
while(b[bi]!=-1){
for(int i=si;i<ai;++i){
if(b[bi]==a[i]){
c[ci++]=a[i];
si=i+1;
break;
}
}
cin>>b[++bi];
}
if(ci&&ai&&bi){
cout<<c[0];
for(int i=1;i<ci;++i)
cout<<" "<<c[i];
}
else cout<<"NULL";
}
#include<iostream>
using namespace std;
struct snodp{
int data;
snodp *next;
};
snodp * crlink(){
snodp * head=0;
int x;
cin>>x;
while(x!=-1){
snodp *p=new snodp;
p->data=x;
p->next=head;
head=p;
cin>>x;
}
return head;
}
snodp * ahave(snodp* a,snodp* b){
snodp * head=new snodp;
head=0;
snodp * b0=new snodp;
b0 =b;
while(a){
b=b0;
while(b){
if(a->data==b->data){
snodp * p=new snodp;
p->data=a->data;
p->next=head;
head=p;
b0=b->next;
break;
}
b=b->next;
}
a=a->next;
}
return head;
}
int main(){
snodp * head0=crlink();
snodp * head1=crlink();
snodp * head3=ahave(head0,head1);
snodp * head=head3;
if(head3)
while(head){
if(head->next!=0)cout<<head->data<<" ";
else cout<<head->data;
head=head->next;
}
else cout<<"NULL";
return 0;
}