问题:给定两个排序后的表L1和L2,写程序仅用基本的表操作来实现L1∩L2和L1∪L2。
思路:本题的前提的是表有序,可以简化对表中元素的遍历操作。
代码:
L2和L2的交操作:
template<typename Object>
list <Object> intersection (const list<Object> &L1,const list<Object> &L2){
list <Object> intersect;
typename list <Object>::const_iterator iter1=L1.begin();
typename list <Object>::const_iterator iter2=L2.begin();
//元素的遍历比较
while(iter1!=L1.end&&iter1!=L2.end()){
if(*iter1== *iter2){
intersect.push_back(*iter1);
iter1++;
iter2++;
}
else if(*iter< *iter2){
iter1++;
}
else iter2++;
}
return intersect;
}
L1和L2的并操作
template <typename Object>
list<Object> listunion(const list<Object> &L1,const list<Object> &L2){
list <Object> listun;
typename list <Object>::const_iterator iter1=L1.begin();
typename list <Object>::const_iterator iter2=L2.begin();
while(iter1!=L1.end()&&iter2!=L2.end()){//元素的遍历比较
if(*iter1== *iter2){
listun.push_back(*iter1);
iter1++;
iter2++;
}
else if(*iter1<*iter2){
listun.push_back(*iter1);
iter1++;
}
else {
listun.push_back(*iter2);
iter2++;
}
}
return listun;
}