// Prog: stack.cpp // implementation of the class ifmp::stack #include #include #include "stack.h" namespace ifmp { // default Constructor stack::stack() : top_node (0) {} // destructor stack::~stack() { clear (top_node); } // copy constructor stack::stack (const stack& s) : top_node (0) { copy (s.top_node, top_node); } // private copy method void stack::copy (const list_node* from, list_node*& to) { assert (to == 0); if (from != 0) { to = new list_node (from->key); copy (from->next, to->next); } } // private clear method void stack::clear (list_node* from) { if (from != 0) { clear (from->next); delete (from); } } // assignment operator stack& stack::operator= (const stack& s) { if (top_node != s.top_node) { // avoid self-assignment clear (top_node); copy (s.top_node, top_node = 0); // top node, set to 0 } return *this; } void stack::push (int key) { top_node = new list_node (key, top_node); } bool stack::empty () const { return top_node == 0; } int stack::top () const { assert (!empty()); return top_node->key; } void stack::pop() { assert (!empty()); list_node* p = top_node; top_node = top_node->next; delete p; } void stack::print (std::ostream& o) const { const list_node* p = top_node; while (p != 0) { o << p->key << " "; p = p->next; } } // POST: s is written to o std::ostream& operator<< (std::ostream& o, const stack& s) { s.print (o); return o; } } // end namespace