/* Code of Figure 10.10, pages 435-436 and Figure 10.11, page 437, from Kenneth C. Louden, Programming Languages Principles and Practice 2nd Edition Copyright (C) Brooks-Cole/ITP, 2003 Test code from pages 438 and 429 also added */ #include using std::cout; using std::endl; // Figure 10.10 code class LinkableObject { public: LinkableObject() : link(0) { } LinkableObject (LinkableObject* p) : link(p) { } LinkableObject* next() { return link; } void linkTo( LinkableObject* p) { link = p; } private: LinkableObject* link; }; // Figure 10.11 code class Queue { public: Queue() : rear(0) { } bool empty() // corrected from int { return rear == 0; } void enqueue(LinkableObject* item); void dequeue(); LinkableObject* front() { return rear->next(); } ~Queue(); protected: // demo - may not be appropriate LinkableObject* rear; }; void Queue::enqueue(LinkableObject* item) { if (empty()) { rear = item; rear->linkTo(item); } else { item->linkTo(front()); rear->linkTo(item); rear = item; } } void Queue::dequeue() { if (front() == rear) rear = 0; else rear->linkTo(front()->next()); } Queue::~Queue() // demo code - may result in dangling refs { while (!empty()) { LinkableObject* temp = front(); dequeue(); delete temp; } } // Code from page 439 class LinkableInt : public LinkableObject { public: LinkableInt(int d) : item(d) { } int data() { return item; } private: int item; }; // test code from pages 438 and 439 int main() { Queue q; LinkableObject* x = new LinkableObject; q.enqueue(x); q.enqueue(new LinkableObject); LinkableObject* y = q.front(); // now y is x if (y == x) cout << "ok!\n"; else cout << "oops!\n"; q.dequeue(); q.dequeue(); // q is now empty if (q.empty()) cout << "ok!" << endl; else cout << "oops!" << endl; { // page 439 LinkableInt* x = new LinkableInt(42); q.enqueue(x); x = static_cast(q.front()); cout << x->data() << endl; // prints 42 } return 0; }