1 /* Stack - a template stack class 2 * 3 * Copyright 2001-2005, Axel Dörfler, axeld@pinc-software.de. 4 * This file may be used under the terms of the MIT License. 5 */ 6 #ifndef STACK_H 7 #define STACK_H 8 9 10 #include <SupportDefs.h> 11 12 13 template<class T> class Stack { 14 public: 15 Stack() 16 : 17 fArray(NULL), 18 fUsed(0), 19 fMax(0) 20 { 21 } 22 23 ~Stack() 24 { 25 free(fArray); 26 } 27 28 bool IsEmpty() const 29 { 30 return fUsed == 0; 31 } 32 33 void MakeEmpty() 34 { 35 // could also free the memory 36 fUsed = 0; 37 } 38 39 status_t Push(T value) 40 { 41 if (fUsed >= fMax) { 42 fMax += 16; 43 T *newArray = (T *)realloc(fArray, fMax * sizeof(T)); 44 if (newArray == NULL) 45 return B_NO_MEMORY; 46 47 fArray = newArray; 48 } 49 fArray[fUsed++] = value; 50 return B_OK; 51 } 52 53 bool Pop(T *value) 54 { 55 if (fUsed == 0) 56 return false; 57 58 *value = fArray[--fUsed]; 59 return true; 60 } 61 62 private: 63 T *fArray; 64 int32 fUsed; 65 int32 fMax; 66 }; 67 68 #endif /* STACK_H */ 69