20-CS-122-001 Computer Science II Spring 2012
Simple List - First Attempt to List A Objects

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

Prev      Next      Lectures      Source

   
#include <iostream>
using namespace std;


class A {
   friend class List;  // Must make List class a friend so it can access next
   friend ostream & operator<<(ostream &, A *);
   int number;
   A *next;            // Why should we have a "next"?
                       // What'f there is a different kind of List to put A in?
public:
   A (int number) { this->number = number; next = NULL; }
};

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

class List {
   A *head;

public:
   List () { head = NULL; }
   
   void add (A *obj) {  obj->next = head;   head = obj;  }
   
   void remove (int number) {
      if (head->number == number) {
	 head = head->next;
	 return;
      }
      for (A *ptr=head ; ptr->next != NULL ; ptr=ptr->next) {
	 if (ptr->next->number == number) {
	    ptr->next = ptr->next->next;
	    return;
	 }
      }
   }

   void show () {
      for (A *ptr = head ; ptr != NULL ; ptr=ptr->next) 
	 cout << ptr->number << " ";
      cout << "\n";
   }
};

int main () {
   List lst;
   lst.add(new A(23));   // Use of add like this looks awful
   lst.add(new A(42));
   lst.add(new A(16));
   lst.add(new A(67));
   lst.show();
   lst.remove(16);       // Use of remove like this looks awful
   lst.show();
   lst.add(new A(16));
   lst.show();
}