数据结构与算法分析 3.4&3.5 — 链表的交与并算法

代码:

 

#include <list>

template<typename ElementType>
list<ElementType> Intersect(const list<ElementType> &list_1, const list<ElementType> &list_2)
{
    list<ElementType> result;
    auto leftPos = list_1.begin( );
    auto rightPos = list_2.begin( );
while (leftPos != list_1.end() && rightPos != list_2.end()) { if (*leftPos > *rightPos) rightPos++; else if (*leftPos < *rightPos) leftPos++; else { result.push_back(*leftPos);++leftPos, ++rightPos; } } return result; } template<typename ElementType> list<ElementType> Union(const list<ElementType> &list_1, const list<ElementType> &list_2 ) { list<ElementType> result; auto leftPos = list_1.cbegin( ); auto rightPos = list_2.cbegin( ); while (leftPos != list_1.end() && rightPos != list_2.end()) { if (*leftPos < *rightPos) result.push_back(*leftPos), ++leftPos; else if (*leftPos > *rightPos) result.push_back(*rightPos), ++rightPos; else { result.push_back(*leftPos); ++leftPos, ++rightPos; } } while (leftPos != list_1.end( )) result.push_back(*leftPos), leftPos++; while (rightPos != list_2.end( )) result.push_back(*rightPos), rightPos++; return result; }

 

posted @ 2015-01-09 20:20  Leptus  阅读(183)  评论(0编辑  收藏  举报