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 <stdlib.h> 11 12 #include <SupportDefs.h> 13 14 15 template<class T> class Stack { 16 public: 17 Stack() 18 : 19 fArray(NULL), 20 fUsed(0), 21 fMax(0) 22 { 23 } 24 25 ~Stack() 26 { 27 free(fArray); 28 } 29 30 bool IsEmpty() const 31 { 32 return fUsed == 0; 33 } 34 35 void MakeEmpty() 36 { 37 // could also free the memory 38 fUsed = 0; 39 } 40 41 status_t Push(T value) 42 { 43 if (fUsed >= fMax) { 44 fMax += 16; 45 T *newArray = (T *)realloc(fArray, fMax * sizeof(T)); 46 if (newArray == NULL) 47 return B_NO_MEMORY; 48 49 fArray = newArray; 50 } 51 fArray[fUsed++] = value; 52 return B_OK; 53 } 54 55 bool Pop(T *value) 56 { 57 if (fUsed == 0) 58 return false; 59 60 *value = fArray[--fUsed]; 61 return true; 62 } 63 64 private: 65 T *fArray; 66 int32 fUsed; 67 int32 fMax; 68 }; 69 70 #endif /* STACK_H */ 71