两个有序链表序列的交集 (20分)(最佳解法)
生活随笔
收集整理的這篇文章主要介紹了
两个有序链表序列的交集 (20分)(最佳解法)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目描述:
已知兩個非降序鏈表序列S1與S2,設計函數(shù)構(gòu)造出S1與S2的交集新鏈表S3。
輸入格式:
輸入分兩行,分別在每行給出由若干個正整數(shù)構(gòu)成的非降序序列,用?1表示序列的結(jié)尾(?1不屬于這個序列)。數(shù)字用空格間隔。
輸出格式:
在一行中輸出兩個輸入序列的交集序列,數(shù)字間用空格分開,結(jié)尾不能有多余空格;若新鏈表為空,輸出NULL。
輸入樣例:
1 2 5 -1
2 4 5 8 10 -1
輸出樣例:
2 5
最開始我的思路是這樣的:List1與List2,嵌套循環(huán), 交集部分壓入List3 , 然后對List3去重,輸出, 這是錯誤的代碼:
#include <iostream> #include <algorithm> #include <cstdio> #include <list>using namespace std ;int main() {list <int> L1 ; //鏈表1 list <int> L2 ; //鏈表2 list <int> L3 ; //交集鏈表 //鏈表1壓入int x1 ;while(scanf("%d",&x1) && x1 != -1) {L1.push_back(x1) ; } //鏈表2壓入int x2 ;while(scanf("%d",&x2) && x2 != -1) {L2.push_back(x2) ; } //迭代器list <int>::iterator it1 ;list <int>::iterator it2 ;list <int>::iterator it3 ; bool flag = false ; //判定新鏈表是否為空。 for ( it1 = L1.begin() ; it1 != L1.end() ; it1++) { for ( it2 = L2.begin() ; it2 != L2.end() ; it2++) {if ( *it1 < *it2 ) {break ; //切記切記 , 這行代碼極易被忽略,它會防止你超時。}if ( *it1 == *it2 ) {int x = *it1 ;flag = true ;L3.push_back(x) ; }}}//去重的兩行代碼。 list<int>::iterator it4 = unique(L3.begin() , L3.end()) ;L3.erase(it4,L3.end()) ; bool flag2 = false ; //判定空格 if ( flag == false ) {cout << "NULL" ; return 0 ;} else {for ( it3 = L3.begin() ; it3 != L3.end() ; it3++ ) {if (flag2 == false) {cout << *it3 ;flag2 = true ;} else {cout << " " << *it3 ;}}}return 0 ; }最后一個測試點死活就過不去,無奈搜網(wǎng),改進后的代碼(全過)
#include <iostream> #include <algorithm> #include <cstdio> #include <list>using namespace std ;int main() {list <int> L1 ; //鏈表1 list <int> L2 ; //鏈表2 list <int> L3 ; //交集鏈表 //鏈表1壓入int x1 ;while(scanf("%d",&x1) && x1 != -1) {L1.push_back(x1) ; } //鏈表2壓入int x2 ;while(scanf("%d",&x2) && x2 != -1) {L2.push_back(x2) ; } /* for ( it2 = L2.begin() ; it2 != L2.end() ; it2++) { cout << *it2 << ' ' ;}*///待會多項式那個用remove試試? //迭代器list <int>::iterator it1 ;list <int>::iterator it2 ;list <int>::iterator it3 ; bool flag = false ; //判定新鏈表是否為空。 //求交集 set_intersection(L1.begin(), L1.end(), L2.begin(), L2.end(), inserter(L3,L3.begin())); if ( !L3.empty() ) flag = true ;bool flag2 = false ; //判定空格 if ( flag == false ) {cout << "NULL" ; return 0 ;} else {for ( it3 = L3.begin() ; it3 != L3.end() ; it3++ ) {if (flag2 == false) {cout << *it3 ;flag2 = true ;} else {cout << " " << *it3 ;}}}return 0 ; }`
WTF???竟然有交集函數(shù)這個東東??
附錄:
對容器L3去重
list::iterator it4 = unique(L3.begin() , L3.end()) ;
L3.erase(it4,L3.end()) ;
交集,并集,差集
set_intersection (取集合交集)
set_union(取集合并集)
set_difference(取集合差集)
總結(jié)
以上是生活随笔為你收集整理的两个有序链表序列的交集 (20分)(最佳解法)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 7-4 求链式线性表的倒数第K项(最佳解
- 下一篇: 算法竞赛入门经典|习题3-8, 循环小数