两个有序链表序列的交集 (20分)(最佳解法)

题目描述:

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。

输入格式:

输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。

输出格式:

在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。

输入样例:

1 2 5 -1
2 4 5 8 10 -1

输出样例:

2 5

最开始我的思路是这样的:List1与List2,嵌套循环, 交集部分压入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 ;
}

最后一个测试点死活就过不去,无奈搜网,改进后的代码(全过)

#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???竟然有交集函数这个东东??

附录:
对容器L3去重

list::iterator it4 = unique(L3.begin() , L3.end()) ;
L3.erase(it4,L3.end()) ;

交集,并集,差集

set_intersection (取集合交集)
set_union(取集合并集)
set_difference(取集合差集)

发布了27 篇原创文章 · 获赞 16 · 访问量 1962

猜你喜欢

转载自blog.csdn.net/weixin_43899069/article/details/104242427