// ********************************************************* // Implementation file StackP.cpp for the ADT stack. // Pointer-based implementation. // ********************************************************* #include "StackP.h" // header file #include // for NULL #include // for assert Stack::Stack() : top(NULL) { } // end default constructor Stack::Stack(const Stack& aStack) { if (aStack.top == NULL) top = NULL; // original list is empty else { // copy first node top = new StackNode(aStack.top->item); // copy rest of list StackNode *newNode = top; // new list pointer for (StackNode *origNode = aStack.top->next; origNode != NULL; origNode = origNode->next) { newNode->next = new StackNode(origNode->item->clone()); newNode = newNode->next; } // end for } // end if } // end copy constructor Stack::~Stack() { popAll(); // Assertion: top == NULL } // end destructor bool Stack::isEmpty() const { return top == NULL; } // end isEmpty void Stack::push(Object* newItem) { // create a new node StackNode *newNode = new StackNode(newItem,top); top = newNode; } // end push Object* Stack::pop() throw(StackException) { if (isEmpty()) throw StackException("StackException: stack empty on pop"); else { // stack is not empty; delete top StackNode *tempNode = top; top = top->next; // return deleted node to system Object* item = tempNode->item; delete tempNode; return item; } // end if } // end pop void Stack::popAll() { while (!isEmpty()) { // stack is not empty; retrieve and delete top delete pop(); } // end if } // end pop const Object* Stack::peek() const throw(StackException) { if (isEmpty()) throw StackException("StackException: stack empty on getTop"); else // stack is not empty; retrieve top return top->item; } // end getTop // End of implementation file.