#ifndef STACK_H_ #define STACK_H_ #include "node.h"; using namespace std; template class Stack { private: // move to front as Iterator at back Node *head; int theSize; public: // create an empty stack Stack(): head(NULL),theSize(0){ } // copy constructor for a stack Stack(const Stack & orig) { *this = orig; } // still must insert copy constructor and assignment operator // destroy nodes in stack ~Stack() { clear(); } Stack & operator= (const Stack & rhs) { if (this != &rhs) { clear(); head = NULL; Node *temp = rhs.head; if (temp != NULL) { head = new Node(temp->getValue()); cout << "head value: " << head->getValue() << endl; Node * current = head; temp = temp->getNext(); while (temp != NULL) { cout << "temp value: " << temp->getValue() << endl; current->setNext(new Node(temp->getValue())); current = current->getNext(); temp = temp->getNext(); } } theSize = rhs.size(); } return *this; } // push elt on the stack void push(T elt) { head = new Node(elt,head); theSize++; } // pop elt from the stack T pop() { Node *temp = head; T topValue = temp->getValue(); head = head->getNext(); theSize--; delete temp; return topValue; } // return top element from the stack T top() const { return head->getValue(); } bool isEmpty() const { return theSize == 0; } void clear() { while (head != NULL) { pop(); } } int size() const { return theSize; } void printString() const { Node *temp = head; cout << "Stack: " << endl; while (temp != NULL) { cout << temp->getValue() << endl; temp = temp->getNext(); } cout << "End of stack" << endl; } // Here is a custom iterator for stacks. The only kind of iterator this data // structure can reasonably support is a forward iterator, so that's // what is provided. It is embedded within // the class it will iterate through to get access to its privates. class Iterator : public std::iterator { public: Iterator(Node* p) : currentNode(p) {} ~Iterator() {} // The assignment and relational operators are straightforward Iterator& operator=(const Iterator& other) { currentNode = other.currentNode; return *this; } bool operator==(const Iterator& other) { return currentNode == other.currentNode; } bool operator!=(const Iterator& other) { return currentNode != other.currentNode; } // Update my state such that I refer to the next element in the // stack. Iterator& operator++() { if (currentNode != NULL) { currentNode = currentNode->getNext(); } return (*this); } Iterator operator++(int) { Iterator tmp(*this); ++(*this); return tmp; } // Return value in the node. Because not return by reference, cannot // update the value. T operator*() { return currentNode->getValue(); } private: Node* currentNode; }; Iterator begin() { return(Iterator(head)); } Iterator end() { return(Iterator(NULL)); } }; #endif /*STACK_H_*/