// This is the implementation file for Display 17.29. // This is the implementation of the class Set. // It is the same as the file set.cpp. #include #include "listtools.h" #include "set.h" using std::cout; using std::endl; using LinkedListSavitch::Node; using LinkedListSavitch::search; using LinkedListSavitch::headInsert; namespace SetSavitch { template Set::Set() { head = NULL; } template Set::~Set() { Node *toDelete = head; while (head != NULL) { head = head->getLink( ); delete toDelete; toDelete = head; } } template bool Set::contains(T target) const { Node* result = search(head, target); if (result == NULL) return false; else return true; } template void Set::output() { Node *iterator = head; while (iterator != NULL) { cout << iterator->getData( ) << " "; iterator = iterator->getLink( ); } cout << endl; } template void Set::add(T item) { if (search(head, item)==NULL) { // Only add the target if it's not in the list headInsert(head, item); } } template Set* Set::setUnion(const Set& otherSet) { Set *unionSet = new Set(); Node* iterator = head; while (iterator != NULL) { unionSet->add(iterator->getData( )); iterator = iterator->getLink( ); } iterator = otherSet.head; while (iterator != NULL) { unionSet->add(iterator->getData( )); iterator = iterator->getLink( ); } return unionSet; } template Set* Set::setIntersection(const Set& otherSet) { Set *interSet = new Set(); Node* iterator = head; while (iterator != NULL) { if (otherSet.contains(iterator->getData( ))) { interSet->add(iterator->getData( )); } iterator = iterator->getLink( ); } return interSet; } } // SetSavitch