#include #include #include "stack.h" // Here we define the IntStackNode struct. struct IntStackNode { // This constructor makes writing IntStack::push() much nicer. IntStackNode( int i, IntStackNode *n ); int item; IntStackNode *next; }; IntStackNode::IntStackNode( int i, IntStackNode *n ) : item( i ) , next( n ) {} IntStack::IntStack() { ptop = NULL; } // The destructor's job is to deallocate all the dynamic memory being // used by the stack. The delAll() helper method does this. IntStack::~IntStack() { delAll(); } // The copy constructor needs to make a duplicate of the stack, which // means it needs to make copies of all the dynamic memory associated with // the other stack. It calls the pushAllFrom() helper method to do this. IntStack::IntStack( const IntStack& other ) { ptop = NULL; pushAllFrom( other.ptop ); } // The assignment operator is kind of like a destructor followed by an // assignment: first blow away whatever this stack is holding onto, then // add in everything the other stack contains. IntStack& IntStack::operator =( const IntStack& other ) { delAll(); ptop = NULL; pushAllFrom( other.ptop ); } bool IntStack::isEmpty() { return ptop == NULL; } void IntStack::push( int item ) { ptop = new IntStackNode( item, ptop ); } int IntStack::pop() { assert( !isEmpty() ); IntStackNode *t = ptop; ptop = ptop->next; int ret = t->item; delete t; return ret; } int IntStack::top() { assert( !isEmpty() ); return ptop->item; } // Deleting everything in the stack is iterative. We use two pointers // to walk across the stack. The first one walks one step ahead, and the // second one cleans up behind it. void IntStack::delAll() { IntStackNode *cur = ptop; IntStackNode *temp; while( cur != NULL ) { temp = cur; cur = cur->next; delete temp; } } // Ah. A beautiful recursive procedure for copying the stack. // This works by first copying everything that's remaining in the stack, // and finally push the current item. If you're not convinced that this // works, you should draw some stacks and which it in action. void IntStack::pushAllFrom( IntStackNode *other ) { if( other != NULL ) { pushAllFrom( other->next ); push( other->item ); } }