home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_08_11 / 8n11087a < prev    next >
Text File  |  1990-09-18  |  2KB  |  60 lines

  1.  
  2. typedef int T;
  3.  
  4. // Boolean type
  5. typedef int Truth;
  6.  
  7. // Node of T is a parametric type.
  8. // A node contains a value of type T.  Each node can link 
  9. // itself to another node
  10. class Node {
  11. public:
  12.      Node( T x)                    { val = x; Next = 0; }
  13.      Node *next()                  { return Next; }
  14.      void link( Node *neighbor)    { Next = neighbor; }
  15.      T value()                     { return val; }
  16. private:
  17.      Node *Next;
  18.      T val;
  19. };
  20.  
  21. // List of T is a Lisp-style list of T values.
  22. class List {
  23. public:
  24.      List()              { head = 0; }
  25.      ~List()             {}
  26.  
  27.      Truth isempty()     { return head == 0; }
  28.  
  29.      // get returns the value at the head of the List
  30.      // without deleting it.  This is car in LISP.
  31.      // precondition:  !isempty() (List is not empty)
  32.      T get()             { return head->value(); }
  33.  
  34.       // add inserts a new element with value x at the head
  35.      // of the List
  36.      void add(T x)
  37.      {
  38.           Node *p = new Node(x);  // error return of new should
  39.                                   // be checked ... 
  40.           if( !isempty() )        // member fun. calls member fun.
  41.                p->link( head);
  42.           head = p;
  43.      }
  44.      
  45.      // del deletes value at the head of the list
  46.      // and returns the value
  47.      // precondition:  !isempty() (List is not empty) 
  48.      T del()
  49.      {
  50.           Node *t = head;
  51.           T r     = head->value();
  52.           head    = head->next();
  53.           delete t;
  54.           return r; 
  55.      }
  56. private:
  57.      Node *head;
  58. };
  59.  
  60.