/* Written by: Iurii Tatishchev ============================= Stack template */ #ifndef STACK_ADT #define STACK_ADT template class Stack { private: // Structure for the stack nodes struct StackNode { T value; // Value in the node StackNode *next; // Pointer to next node }; StackNode *top; // Pointer to the stack top int length; public: // Constructor Stack(){ top = nullptr; length = 0; } // Destructor ~Stack(); // Stack operations: bool push(T item); T pop(); T peek() { return top->value; }; bool isEmpty() { return length == 0; }; int getLength() { return length; } ; }; /* Member function push inserts the argument onto the stack. */ template bool Stack::push(T item) { StackNode *newNode; // Pointer to a new node // Allocate a new node and store item there. newNode = new StackNode; if (!newNode) return false; newNode->value = item; // Update links and counter newNode->next = top; top = newNode; length++; return true; } /* Member function pop deletes the value at the top of the stack and returns it. Assume stack is not empty. */ template T Stack::pop() { T val = this->top->value; StackNode* oldTop = this->top; this->top = this->top->next; this->length--; delete oldTop; return val; } /* Destructor: Traverses the list deleting each node (without calling pop) */ template Stack::~Stack() { StackNode *currNode; // Position nodePtr at the top of the stack. currNode = top; // Traverse the list deleting each node. while (currNode) { StackNode* nextNode = currNode->next; delete currNode; currNode = nextNode; } } #endif