[8]
DejaVU Online:
Principles of Object-Oriented Software Development
(©)
typedef int element;
enum { NIL, CONS };
struct list {
int tag;
element e;
list* next;
};
list* nil() { nil
list* l = new list; l->tag = NIL; return l;
}
list* cons( element e, list* l) { cons
list* x = new list;
x->tag = CONS; x->e = e; x->next = l;
return x;
}
int empty(list* lst) { return !lst || lst->tag == NIL; }
element head(list* l) { head
require( ! empty(l) );
return l->e;
}
list* tail(list* l) { tail
require( ! empty(l) );
return l->next;
}
bool equal(list* l, list* m) { equal
switch( l->tag) {
case NIL: return empty(m);
case CONS: return !empty(m) &&
head(l) == head(m) &&
tail(l) == tail(m);
}
}
list* r = cons(1,cons(2,nil()));
while (!empty(r)) {
cout << head(r) << endl;
r = tail(r);
}
template< class E >
class nil : public list< E > { nil
public:
nil() {}
bool empty() { return 1; }
E head() { require( false ); return E(); }
list< E >* tail() { require( 0 ); return 0; }
bool operator==(list<E>* m) { return m->empty(); }
};
template< class E >
class cons : public list< E > { cons
public:
cons(E e, list<E>* l) : _e(e), next(l) {}
~cons() { delete next; }
bool empty() { return 0; }
E head() { return _e; }
list<E>* tail() { return next; }
bool operator==(list<E>* m);
protected:
E _e;
list<E>* next;
};
list<int>* r = new cons<int>(1, new cons<int>(2, new nil<int>));
while (! r->empty()) {
cout << r->head() << endl;
r = r->tail();
}
delete r;
|
Hush Online Technology
hush@cs.vu.nl
12/29/99 |
|
|