#include #include // first version. Link and List are nothing new. // List has a special method called do_to_all. You // give it a function of the right type, and it // runs that function on every element of the list. // This is a mostly unsatisfactory solution, it // requires a global variable just for something // as simple as finding the smallest. struct Link { int data; Link * next; Link(int d, Link * n); }; Link::Link(int d, Link * n) { data = d; next = n; } class List { protected: Link * first; public: List(); void add(int x); void do_to_all(void operation(Link *)); }; List::List() { first = NULL; } void List::add(int x) { first = new Link(x, first); } void List::do_to_all(void operation(Link *)) { Link * ptr = first; while (ptr!=NULL) { operation(ptr); ptr = ptr->next; } } void printer(Link * p) { cout << p->data << "\n"; } void list_multiples_of_eleven(Link * p) { if (p->data%11==0) cout << p->data << " is a multiple of 11\n"; } int evil_global_variable; void find_smallest(Link * p) { if (p->data < evil_global_variable) evil_global_variable = p->data; } void main() { List L; L.add(235); L.add(65); L.add(8278); L.add(99); L.add(3); L.add(198); L.add(642); L.do_to_all(printer); L.do_to_all(list_multiples_of_eleven); evil_global_variable = INT_MAX; L.do_to_all(find_smallest); cout << "The smallest is " << evil_global_variable << "\n"; }