两个有序链表序列的交集
7-52 两个有序链表序列的交集 (20 分)
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
输入样例:
1 2 5 -1
2 4 5 8 10 -1
输出样例:
2 5
1 #include <iostream> 2 #include <list> 3 #include <algorithm> 4 using namespace std; 5 int main(){ 6 list<int> myList1; 7 list<int> myList2; 8 list<int> myList3; 9 int n; 10 while(cin >> n, n != -1){ 11 myList1.push_back(n); 12 } 13 while(cin >> n, n != -1){ 14 myList2.push_back(n); 15 } 16 set_intersection(myList1.begin(), myList1.end(), myList2.begin(), myList2.end(), inserter(myList3,myList3.begin())); 17 if(!myList3.empty()){ 18 for(list<int>::iterator it = myList3.begin(); it != myList3.end(); it++){ 19 if(it == myList3.begin()){ 20 cout << *it; 21 } 22 else{ 23 cout << ' ' << *it; 24 } 25 } 26 } 27 else{ 28 cout << "NULL"; 29 } 30 31 return 0; 32 }
浙公网安备 33010602011771号