<span style="color:#339999;">《数据结构与算法分析》练习3.4和3.5让求两个排序后的表的并集和交集,看到一篇</span><a target=_blank href="http://blog.csdn.net/jshmqjw/article/details/8977549" target="_blank"><span style="color:#ff0000;">博客</span></a><span style="color:#339999;">给出了代码,受启发自己写了一段,其中用到了那篇博客的部分代码,在此表示感谢。</span><p><span style="color:#339999;"> 我的主要想法是,由于表是排序后的,不断判断两个表的第一个值。求交集时,只取两者相等的值,而把小的那一个值去掉;求并集时,取小的那个值和相等的值,然后把小的那个值和相等的值去掉,注意最后由于可能一方先为empty,所以最后需要merge一下。话不多说,上代码:</span></p>
#include <list>
#include "stdlib.h"
using namespace std;
void showList(list<int> t){
while (!t.empty()){
printf("%d ", t.front());
t.pop_front();
}
printf("\n");
}
int main(){
int a[8] = {0, 2, 3, 5, 6, 7, 9, 12};
int b[8] = {1, 2, 4, 5, 7, 8, 9, 13};
list<int> lt1(a, a+8);
list<int> lt2(b, b+8);
list<int> lt3(a, a+8);
list<int> lt4(b, b+8);
list<int> ltr1, ltr2;
//求交集
if(lt1.empty() || lt2.empty())
{
return 0;
}
while (!lt1.empty() && !lt2.empty())
{
if(lt2.front()>lt1.front())
{
lt1.pop_front();
continue;
}
if(lt2.front()==lt1.front())
{
ltr1.push_back(lt1.front());
lt1.pop_front();
lt2.pop_front();
continue;
}
if(lt2.front()<lt1.front())
{
lt2.pop_front();
continue;
}
}
printf(<span class="string">"the intersection of the two sets is: "</span><span>); </span>
showList(ltr1);
<pre class="cpp" name="code"> //求并集
if(lt3.empty())
{
showList(lt2);
return 0;
}
if(lt4.empty())
{
showList(lt1);
return 0;
}
while (!lt3.empty() && !lt4.empty())
{
if(lt4.front()>lt3.front())
{
ltr2.push_back(lt3.front());
lt3.pop_front();
continue;
}
if(lt4.front()==lt3.front())
{
ltr2.push_back(lt3.front());
lt3.pop_front();
lt4.pop_front();
continue;
}
if(lt4.front()<lt3.front())
{
ltr2.push_back(lt4.front());
lt4.pop_front();
continue;
}
}
ltr1.merge(lt3);
ltr1.merge(lt4);
printf(<span class="string">"the union of the two sets is: "</span><span>); </span>
showList(ltr2);
return 0;
}