20-CS-122-001 Computer Science II Spring 2012
Simple List - Use void* to eliminate next in A

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

Prev      Next      Lectures      Source

#include <iostream>
using namespace std;

// Use void* and class Cell to eliminate the need for next in class A
class A {
   friend class List; // Still a friend of List!!
   friend ostream & operator<<(ostream &out, A *a);
   int number;

public:
   A (int number) { this->number = number; }
};

ostream & operator<<(ostream &out, A *a) {
   out << a->number;
   return out;
}

class Cell {
   friend class List;
   friend ostream &operator<<(ostream &, List &);
   void *item;
   Cell *next;
   Cell (void *item, Cell *next) { this->item = item; this->next = next; }   
};

class List {
   friend ostream & operator<<(ostream &, List &);
   Cell *head;

public:
   List () { head = NULL; }
   
   void operator+=(void *obj) {  head = new Cell(obj, head);  } // Now void*
   
   void operator-=(int number) {
      if (((A*)head->item)->number == number) { // Specify A to access number
	 Cell *temp = head;    // Added
	 head = head->next;
	 delete temp;          // Added
	 return;
      }
      for (Cell *ptr=head ; ptr->next != NULL ; ptr=ptr->next) {
	 if (((A*)ptr->next->item)->number == number) { // Specify A for number
	    Cell *temp = ptr->next;      // Added
	    ptr->next = ptr->next->next;
	    delete temp;                 // Added
	    return;
	 }
      }
   }
};

ostream &operator<<(ostream &out, List &lst) {
   for (Cell *ptr = lst.head ; ptr != NULL ; ptr=ptr->next) 
      out << ((A*)ptr->item) << " ";
   return out;
}

int main () {
   List lst;
   lst += new A(23);
   lst += new A(42);
   lst += new A(16);
   lst += new A(67);
   cout << lst << "\n";
   lst -= 16;
   cout << lst << "\n";
   lst += new A(16);
   cout << lst << "\n";
}