#ifndef Stack_H #define Stack_H #include template class Stack { public: Stack(); ~Stack(); void push(const T); T pop(); T peek(); int stackCount(); private: bool isEmpty(); bool isFull(); void resize(int); static const int defSize = 4; T* stackPointer; int sSize, top; }; template Stack::Stack(){ top = 0; stackPointer = (T*)malloc(sizeof(T) * defSize); if(stackPointer == NULL) { if(Serial) { Serial.println("Could not create stack"); } } sSize = defSize; } template Stack::~Stack() { free(stackPointer); } template void Stack::push(const T t){ if(isFull()) { resize(sSize * 2); } stackPointer[top++] = t; } template T Stack::pop() { if(isEmpty()) { if(Serial) { Serial.println("Stack pop failed as empty"); } } T t = stackPointer[--top]; // think about resizing if(top <= sSize / 4 && sSize > defSize) { resize(sSize / 2); } return t; } template T Stack::peek() { if(isEmpty()) { if(Serial) { Serial.println("No items in stack"); } } else { T t = stackPointer[top - 1]; return t; } } template int Stack::stackCount() { return top; } // now the private methods template bool Stack::isEmpty() { return (top == 0); } template bool Stack::isFull() { return (top == sSize); } template void Stack::resize(int newSize) { stackPointer = (T *)realloc(stackPointer, sizeof(T) * newSize); if(stackPointer == NULL) { if(Serial) { Serial.println("Stack resize failed"); } } sSize = newSize; } #endif