// Simple implementation of a type parameterized Set container #ifndef _SET_H #define _SET_H #include using namespace std; template class Set { public: // Constructor and destructor Set() : head(NULL) { } ~Set() { release(); } // Copy constructor Set(const Set & s) { copy(s); } // Assignment of sets Set & operator = (const Set & s) { if (this != & s) { release(); copy(s); } return *this; } // Check if a value is in the set bool contains(const TYPE & v) { for (Item * cur = head; cur != NULL; cur = cur->next) if (cur->value == v) return true; return false; } // Add the value to set if not already there void add(const TYPE & v) { if (contains(v)) return; Item * newitem = new Item(v); if (head != NULL) newitem->next = head; head = newitem; } // Remove the value if it's there void remove(const TYPE & v) { for (Item *prev = NULL, *cur = head; cur != NULL; prev = cur, cur = cur->next) { if (cur->value == v) { Item * tmp = cur->next; delete cur; if (prev == NULL) head = tmp; else prev->next = tmp; return; } } } // Display the set ostream & print(ostream & o) const { for (Item * cur = head; cur != NULL; cur = cur->next) { if (cur != head) o << ' '; o << cur->value; } return o; } private: // Private structure for value and linkage struct Item { TYPE value; Item * next; Item(const TYPE & v, Item * n = NULL) : value(v), next(n) { } }; Item * head; // Delete all items in set - used by destructor and assignment void release() { Item * cur = head; while (cur != NULL) { Item * tmp = cur; cur = cur->next; delete tmp; } } // Copy the set - used by copy constructor and assignment void copy(const Set & s) { Item * cur = NULL; for (Item * exist = s.head; exist != NULL; exist = exist->next) { Item * newitem = new Item(exist->value); if (cur == NULL) head = cur = newitem; else { cur->next = newitem; cur = cur->next; } } } }; template inline ostream & operator << (ostream & o, const Set & s) { return s.print(o); } #endif