// // example of using recursive linked-list class: // // define and illustrate use of "shopping list" class. // // version 1 // #include #include // has EXIT_SUCCESS #include #include "seq.h" // has Seq template class // // "shopping list" class // class ShopList { public: // public interface for class: // constructor. // post: constructed ShopList has no items. ShopList() { items = Seq(); } // function to print items. // post: all items in list printed to stdout. void printItems() const { print(items); } // function to search for item. // post: returns true if itm is in list, false otherwise. bool hasItem(const string & itm) const { return has(itm, items); } // function to add item. // post: "itm" added to list. void addItem(const string & itm) { items = Seq(itm, items); } // function to remove item. // post: "itm" removed from list if present. // (removes first occurrence only.) void removeItem(const string & itm) { items = remove(itm, items); } private: // list of items. Seq items; // helper functions: // function to print list of strings. // post: l printed to stdout. static void print(const Seq & l) { if (l.empty()) return; else { cout << l.hd() << endl; print(l.tl()); } } // function to find item in list of strings. // post: returns true if itm is in l, false otherwise. static bool has(const string & itm, const Seq & l) { if (l.empty()) return false; else return (l.hd() == itm) || has(itm, l.tl()); } // function to remove item from list of strings. // post: returns l with first occurrence of itm removed. static Seq remove(const string & itm, const Seq & l) { if (l.empty()) return l; else if (l.hd() == itm) return l.tl(); else return Seq(l.hd(), remove(itm, l.tl())); } }; // // main program: // // illustrates use of ShopList class. // int main(void) { ShopList myList; cout << "Items on my list:\n"; myList.printItems(); myList.addItem("soda pop"); myList.addItem("paper towels"); cout << "Items on my list after add:\n"; myList.printItems(); cout << "Is soda pop on my list? "; if (myList.hasItem("soda pop")) cout << "yes\n"; else cout << "no\n"; cout << "Is beer on my list? "; if (myList.hasItem("beer")) cout << "yes\n"; else cout << "no\n"; myList.removeItem("paper towels"); cout << "Items on my list after remove:\n"; myList.printItems(); return EXIT_SUCCESS; }