20-CS-122-001 Computer Science II Spring 2012
Queue Class - Not General

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      Lectures     q.1.cc     queue.1.h     queue.1.cc

#include <iostream>
using namespace std;

class Queue;

class Cell {
friend ostream & operator<<(ostream & out, Queue &lst);
friend class Queue;
   Cell *next; void *object;
   Cell (void *o, Cell *n) { next = n; object = o; }
};

class Queue {
friend ostream & operator<<(ostream & out, Queue &que);
   Cell *tail;

public:
   Queue() { tail = NULL;  }

   void enqueue(void *t) {
      if (t == NULL) return;
      if (tail == NULL) {
         tail = new Cell(t, NULL);
         tail->next = tail;
      } else {
         Cell *h = new Cell(t, tail->next);
         tail->next = h;
         tail = h;
      }
   }

   void *dequeue() {
      if (tail == NULL) return NULL;
      Cell *ptr = tail->next;
      void *t = ptr->object;
      if (ptr != tail) tail->next = ptr->next; else tail = NULL;
      delete ptr;
      return t;
   }

   bool isEmpty() {  return tail == NULL;  }
};

ostream & operator<<(ostream & out, Queue &que) {
   Cell *t;
   if (que.isEmpty()) { 
      out << "(empty)";
   } else {
      for (Cell *ptr=que.tail->next ; ptr != que.tail ; ptr=ptr->next)
         out << *((int *)(ptr->object)) << " ";
      out << *((int *)(que.tail->object));
   }   
   out << "\n";
   return out;
}

int main () {
   Queue q;
   cout << q;
   q.enqueue(new int(3));
   cout << q;
   q.enqueue(new int(6));
   cout << q;
   q.enqueue(new int(9));
   q.enqueue(new int(12));
   q.enqueue(new int(15));
   cout << q;
   int result = *(int *)q.dequeue();
   cout << "-----------\n";
   cout << "Popped Result: " << result << "\nQueue: " << q << "\n";
   q.enqueue(new int(18));
   cout << q;
   cout << "-----------\n";
   result = *(int *)q.dequeue();
   cout << "Popped Result: " << result << "\n";
   result = *(int *)q.dequeue();
   cout << "Popped Result: " << result << "\nQueue: " << q << "\n";
}