// File: PersonSet.cpp // Author: Karl Abrahamson #include #include "Person.h" #include "PersonSet.h" using namespace std; PersonSet::PersonSet() { who = NULL; next = NULL; } PersonSet::PersonSet(const Person* p, const PersonSet* s) { who = p; next = s; } bool PersonSet::isEmpty() const { return who == NULL; } const Person* PersonSet::getFirst() const { return who; } const PersonSet* PersonSet::getRest() const { return next; } const PersonSet* PersonSet::insert(const Person* p) const { if(isEmpty()) return new PersonSet(p, this); else { int c = p->compare(getFirst()); if(c == 0) return this; else if(c < 0) { return new PersonSet(p, this); } else { return new PersonSet(getFirst(), getRest()->insert(p)); } } } const PersonSet* PersonSet::remove(const Person* p) const { if(isEmpty()) return this; else if(p->equal(getFirst())) return getRest(); else { const PersonSet* a = getRest()->remove(p); return a->insert(getFirst()); } } int PersonSet::cardinality() const { if(isEmpty()) return 0; else return 1 + getRest()->cardinality(); } long PersonSet::hash() const { if(isEmpty()) return 0; else { long h1 = strhash(getFirst()->getName()); long h2 = getRest()->hash(); return labs(h1/3 + h2/2); } } bool PersonSet::equal(const PersonSet* s) const { if(isEmpty() != s->isEmpty()) return false; if(isEmpty()) return true; if(!getFirst()->equal(s->getFirst())) return false; return getRest()->equal(s->getRest()); } void PersonSet::print() const { cout << "{"; printMems(); cout << "}"; } void PersonSet::printMems() const { if(!isEmpty()) { who->print(); if(!next->isEmpty()) { cout << ", "; next->printMems(); } } }