#ifndef SMART_STACK_H_ #define SMART_STACK_H_ #include // includes defintions for size_t and NULL #include #include #include using namespace std; template class stack { public: stack() : top_of_stack(NULL), num_items(0) { } size_t size() const { return num_items; } bool empty() const { return num_items == 0; } void push(const Item_Type& item) { top_of_stack = new Node(item, top_of_stack); num_items++; } const Item_Type& top() const { return top_of_stack->data; } void pop() { Node* old_top = top_of_stack; top_of_stack = top_of_stack->next; delete old_top; num_items--; } // Housekeeping functions ~stack() { while (!empty()) pop(); } stack(const stack& other) : top_of_stack(NULL), num_items(other.num_items) { Node *prev, *walk; // Note use of asterisk for *walk walk = other.top_of_stack; prev = NULL; while (walk != NULL) { Node* temp = new Node(walk->data); if (prev != NULL) prev->next = temp; else top_of_stack = temp; prev = temp; walk = walk->next; } } void swap(stack& other) { std::swap(num_items, other.num_items); std::swap(top_of_stack, other.top_of_stack); } stack& operator=(const stack& other) { if (this != &other) { stack temp(other); swap(temp); } return *this; } //----------------------------------------------------------- // used for diagnostic purposes to count number of live nodes static int total; static int getTotalNumNodes() { return total; } std::string dump() const { std::stringstream temp; for (Node* walk=top_of_stack; walk!=NULL; walk=walk->next) temp << walk->data << " "; return temp.str(); } //----------------------------------------------------------- private: struct Node { Item_Type data; /** The data */ Node* next; /** The pointer to the next node. */ Node(const Item_Type& data_item, Node* next_ptr = NULL) : data(data_item), next(next_ptr) { stack::total++; // please leave this command here } ~Node() { stack::total--; // please leave this command here } }; // data members Node* top_of_stack; /** A pointer to the top of the stack */ size_t num_items; }; // End class stack #endif