//-------------------------------------------------------------------- // // Laboratory 5 stackarr.cpp // // SOLUTION: Array implementation of the Stack ADT // //-------------------------------------------------------------------- #include #include "stackarr.h" //-------------------------------------------------------------------- template < class SE > Stack:: Stack ( int maxNumber ) // Creates an empty stack. Allocates enough memory for maxNumber // elements (defaults to defMaxStackSize). : maxSize(maxNumber), top(-1) { element = new SE [ maxSize ]; assert ( element != 0 ); } //-------------------------------------------------------------------- template < class SE > Stack:: ~Stack () // Frees the memory used by a stack. { delete [] element; } //-------------------------------------------------------------------- template < class SE > void Stack:: push ( const SE &newElement ) // Inserts newElement onto the top of a stack. { assert ( top < maxSize ); // Requires that the stack is not full element[++top] = newElement; } //-------------------------------------------------------------------- template < class SE > SE Stack:: pop () // Removes the topmost element from a stack and returns it. { assert ( top != -1 ); // Requires that the stack is not empty return element[top--]; } //-------------------------------------------------------------------- template < class SE > void Stack:: clear () // Removes all the elements from a stack. { top = -1; } //-------------------------------------------------------------------- template < class SE > int Stack:: empty () const // Returns 1 if a stack is empty. Otherwise, returns 0. { return ( top == -1 ); } //-------------------------------------------------------------------- template < class SE > int Stack:: full () const // Returns 1 if a stack is full. Otherwise, returns 0. { return ( top == maxSize - 1 ); } //-------------------------------------------------------------------- template < class SE > void Stack:: showStructure () const // Array implementation. Outputs the elements in a stack. If the // stack is empty, outputs "Empty stack". This operation is intended // for testing and debugging purposes only. { int j; // Loop counter if ( top == -1 ) cout << "Empty stack" << endl; else { cout << "top = " << top << endl; for ( j = 0 ; j < maxSize ; j++ ) cout << j << "\t"; cout << endl; for ( j = 0 ; j <= top ; j++ ) cout << element[j] << "\t"; cout << endl; } }