#include<iostream> #include<algorithm> #include<map> #include<list> void calculateUnion(const std::list<int>& list1, const std::list<int>& list2, std::list<int>& outputResult) { std::map< int, bool> tmp; for (auto iter : list1) { if (tmp.find(iter) == tmp.end()) tmp.insert(std::make_pair(iter, true)); } for (auto iter : list2) { if (tmp.find(iter) == tmp.end()) tmp.insert(std::make_pair(iter, true)); } //convert map to list for (auto iter : tmp) { if (iter.second) outputResult.push_back(iter.first); } } void calculateIntersection(const std::list<int>& list1, const std::list<int>& list2, std::list<int>& outputResult) { std::map< int, bool> tmp; for (auto iter : list1) { tmp.insert(std::make_pair(iter, false)); } for (auto iter : list2) { if (tmp.find(iter) != tmp.end()) outputResult.push_back(iter); } } int main() { //list1: 10->15->4->20 //list2: 8->4->2->10 std::list< int> list1, list2, result; list1.push_back(10); list1.push_back(15); list1.push_back(4); list1.push_back(20); list2.push_back(8); list2.push_back(4); list2.push_back(2); list2.push_back(10); calculateUnion(list1, list2, result); std::cout << "union result: \n"; std::for_each(result.begin(), result.end(), [](const int& value){ std::cout << value << " "; }); result.clear(); calculateIntersection(list1, list2, result); std::cout << "\nintersection result: \n"; std::for_each(result.begin(), result.end(), [](const int& value){ std::cout << value << " "; }); std::cout << std::endl; return 0; }输出:
哈希(4) - 求两个链表的交集(intersection)以及并集(union)
原文地址:http://blog.csdn.net/shltsh/article/details/46484673