1-7 两个有序链表序列的交集 (20分) 已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
输入格式: 输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式: 在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
输入样例: 1 2 5 -1 2 4 5 8 10 -1 输出样例: 2 5
#include<bits/stdc++.h> #include<vector> using namespace std; vector<int> s1,s2; int main() { ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int num; while(1){ cin>>num; if(num==-1) break; else s1.push_back(num); } while(1){ cin>>num; if(num==-1) break; else s2.push_back(num); } int i=0,j=0,flag=0; if (s1.size()==0||s2.size()==0) { cout<<"NULL"; } else { while(i<s1.size()&&j<s2.size()) { if (s1[i]==s2[j]) { if (flag) cout<<" "; cout<<s1[i]; flag=1; i++; j++; } else if(s1[i]>s2[j]) { j++; } else { i++; } } if(flag==0) cout<<"NULL"; } }