home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C16 / TStack.h < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.9 KB  |  86 lines

  1. //: C16:TStack.h
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Stack using templates
  7. #ifndef TSTACK_H
  8. #define TSTACK_H
  9.  
  10. // Declaration required:
  11. template<class T> class TStackIterator;
  12.  
  13. template<class T> class TStack {
  14.   struct Link {
  15.     T* data;
  16.     Link* next;
  17.     Link(T* dat, Link* nxt) {
  18.       data = dat;
  19.       next = nxt;
  20.     }
  21.   }* head;
  22.   int _owns;
  23. public:
  24.   TStack(int own = 1) : head(0), _owns(own) {}
  25.   ~TStack();
  26.   void push(T* dat) {
  27.     head = new Link(dat,head);
  28.   }
  29.   T* peek() const { return head->data; }
  30.   T* pop();
  31.   int owns() const { return _owns; }
  32.   void owns(int newownership) {
  33.     _owns = newownership;
  34.   }
  35.   friend class TStackIterator<T>;
  36. };
  37.  
  38. template<class T> T* TStack<T>::pop() {
  39.   if(head == 0) return 0;
  40.   T* result = head->data;
  41.   Link* oldHead = head;
  42.   head = head->next;
  43.   delete oldHead;
  44.   return result;
  45. }
  46.  
  47. template<class T> TStack<T>::~TStack() {
  48.   Link* cursor = head;
  49.   while(head) {
  50.     cursor = cursor->next;
  51.     // Conditional cleanup of data:
  52.     if(_owns) delete head->data;
  53.     delete head;
  54.     head = cursor;
  55.   }
  56. }
  57.  
  58. template<class T> class TStackIterator {
  59.   TStack<T>::Link* p;
  60. public:
  61.   TStackIterator(const TStack<T>& tl)
  62.     : p(tl.head) {}
  63.   TStackIterator(const TStackIterator& tl)
  64.     : p(tl.p) {}
  65.   // operator++ returns boolean indicating end:
  66.   int operator++() {
  67.     if(p->next)
  68.       p = p->next;
  69.     else p = 0; // Indicates end of list
  70.     return int(p);
  71.   }
  72.   int operator++(int) { return operator++(); }
  73.   // Smart pointer:
  74.   T* operator->() const {
  75.     if(!p) return 0;
  76.     return p->data;
  77.   }
  78.   T* current() const {
  79.     if(!p) return 0;
  80.     return p->data;
  81.   }
  82.   // int conversion for conditional test:
  83.   operator int() const { return p ? 1 : 0; }
  84. };
  85. #endif // TSTACK_H ///:~
  86.