00001 /*************************************************************************** 00002 stack.h - Definition of Stack template class. 00003 ------------------- 00004 begin : June 21 2002 00005 copyright : (C) 2003 by Vojtìch Toman 00006 email : vtoman@lit.cz 00007 ***************************************************************************/ 00008 00009 /*************************************************************************** 00010 * * 00011 * This program is free software; you can redistribute it and/or modify * 00012 * it under the terms of the GNU General Public License as published by * 00013 * the Free Software Foundation; either version 2 of the License, or * 00014 * (at your option) any later version. * 00015 * * 00016 ***************************************************************************/ 00017 00025 #ifndef STACK_H 00026 #define STACK_H 00027 00028 00029 #include "defs.h" 00030 #include "collection.h" 00031 #include "debug.h" 00032 00033 00037 template<class T_> struct StackLinkedList 00038 { 00040 struct StackLinkedList<T_> *prev_; 00041 00043 T_ *data_; 00044 00045 }; //StackLinkedList 00046 00047 00051 template<class T_> class Stack : public Collection<T_> 00052 { 00053 public: 00059 Stack(void) : Collection<T_>() { initStack(); } 00060 00066 virtual ~Stack(void) { clear(); } 00067 00068 00069 00077 virtual T_ *top(void) 00078 { 00079 if (!topNode_) 00080 return 0; 00081 else 00082 { 00083 return topNode_->data_; 00084 } 00085 } 00086 00087 00088 00094 virtual void push(T_ *item) 00095 { 00096 StackLinkedList<T_> *pom; 00097 00098 NEW(pom, StackLinkedList<T_>); 00099 00100 pom->data_ = item; 00101 00102 if (!topNode_) 00103 pom->prev_ = 0; 00104 else 00105 pom->prev_ = topNode_; 00106 00107 topNode_ = pom; 00108 00109 cnt_++; 00110 } 00111 00112 00113 00119 virtual T_ *pop(void) 00120 { 00121 if (!topNode_) 00122 return 0; 00123 else 00124 { 00125 StackLinkedList<T_> *pom; 00126 T_ *data; 00127 00128 pom = topNode_; 00129 data = topNode_->data_; 00130 00131 topNode_ = topNode_->prev_; 00132 00133 cnt_--; 00134 00135 DELETE(pom); 00136 return data; 00137 } 00138 } 00139 00140 00141 00149 virtual void clear(void) 00150 { 00151 StackLinkedList<T_> *pom; 00152 00153 while (topNode_) 00154 { 00155 pom = topNode_; 00156 topNode_ = topNode_->prev_; 00157 00158 if (autoDelete_) 00159 DELETE(pom->data_); 00160 00161 DELETE(pom); 00162 } 00163 00164 topNode_ = 0; 00165 cnt_ = 0; 00166 } 00167 00168 00169 00170 00171 protected: 00173 struct StackLinkedList<T_> *topNode_; 00174 00176 virtual void initStack(void) 00177 { 00178 topNode_ = 0; 00179 } 00180 00181 }; //Stack 00182 00183 00184 #endif //STACK_H