|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
问题:给定两个排序后的表L1和L2,写程序用表的基本操作来实现L1和L2的交集与并集,代码如下:
- #include <iostream>
- #include <list>
- using namespace std;
- void printlist (const list<int> &s);
- list<int> jiao_ji (list<int> L1,list <int>L2);
- list<int> bing_ji (list<int> L1,list <int>L2);
- int main()
- {
- int num_1[11]={1,2,3,5,7,9,10,12,17,20,23}; //int num_1[11]={1,2,3,5,7,9,10,12,17,20,23};
- int num_2[8] = {0,2,3,5,9,10,13,24}; //int num_2[8] = {0,2,3,5,9,10,13,22};
- list <int >L1(num_1,num_1+11);
- list<int> L2(num_2,num_2+8);
- printlist(L1);
- cout<<endl;
- printlist(L2);
- cout<<endl;
- list <int >jiao;
- list <int >bing;
- jiao=jiao_ji(L1,L2);
- cout<<"L1和L2的交集是:";
- printlist(jiao);
- cout<<endl;
- bing=bing_ji(L1,L2);
- cout<<"L1和L2的并集是:";
- printlist(bing);
- cout<<endl;
- return 0;
- }
- //求交集
- list<int> jiao_ji (list<int> L1,list <int>L2)//[color=Red]存在一个问题,当L2先为空或者二者同时为空是就出现问题,当L1先为空时则没有问题???
- [/color]{
- list <int >temp;
- while(!L1.empty ()&&!L2.empty ())
- {
- int k=L1.front ();
- if (k<L2.front ())
- L1.pop_front ();
- else
- {
- while (k>=L2.front() &&!L2.empty ())
- {
- if (k==L2.front ()){
- temp.push_back (k);
- L1.pop_front ();
- L2.pop_front ();
- }
- else
- L2.pop_front ();
- }
- }
- }
- return temp;
- }
- //求并集
- list<int> bing_ji (list<int> L1,list <int>L2)
- {
- list <int> temp;
- while (!L1.empty ()&&!L2.empty ())
- {
- int k=L1.front ();
- if (k<L2.front ())
- {
- temp.push_back (k);
- L1.pop_front ();
- }
- else if (k==L2.front ())
- {
- temp.push_back (k);
- L1.pop_front ();
- L2.pop_front ();
- }
- else
- {
- while (k>L2.front ()&&!L2.empty ())
- {
- temp.push_back (L2.front ());
- L2.pop_front ();
- }
- }
- }
-
- if (L1.empty ())
- while (!L2.empty ()){
- temp.push_back (L2.front ());
- L2.pop_front ();
- }
- if (L2.empty ())
- while (!L1.empty ()){
- temp.push_back (L1.front ());
- L1.pop_front ();
- }
- return temp;
- }
- void printlist (const list<int> &s)
- {
- list<int>::const_iterator it=s.begin ();
- while (it!=s.end()){
- cout<<*it++<<' ';
- }
- }
复制代码
问题就是在求交集是表L1先为空是就正常,而当L2先为空或者同时为空时则出现debug assertion failed错误,例如我在两个整型数组后面注释的那样的数组就不行,请各位大神显灵 啊啊啊啊啊啊啊…… |
|