// FILE: StacktS.cpp // FILES NEEDED: Stackt.h //*** Stack of NodeType implemented as linked list #ifndef STACK_CPP #define STACK_CPP #include "Stackt.h" #include #include template Stack::Stack(void) { myTop = NULL; } //*** default constructor template Stack::Stack(const Stack &s) { if ( s.myTop == NULL ) { myTop = NULL; return; } NodeType *curr = myTop = new NodeType, *source = s.myTop; for (;;) { curr->info = source->info; source = source->next; if (source == NULL ) break; curr->next = new NodeType; curr = curr->next; } curr->next = NULL; } //*** copy constructor template Stack::~Stack(void) { makeEmpty(); } template void Stack::push(const T &item) { NodeType *np = new NodeType; np->info = item; np->next = myTop; myTop = np; } //*** push template void Stack::pop(T &item) { if ( !isEmpty() ) { item = myTop->info; NodeType *curr = myTop; myTop = myTop->next; delete curr; } else item = T(); } //*** pop template Stack &Stack::operator=(Stack &rhs) { if ( this == &rhs ) return *this; makeEmpty(); if ( rhs.myTop == NULL ) return *this; NodeType *source(rhs.myTop), *np; np = myTop = new NodeType; for (;;) { np->info = source->info; source = source->next; if ( source == NULL ) break; np->next = new NodeType; np = np->next; } np->next = NULL; return *this; } /*--------------------------------------------- // overloaded = operator: vector approach //--------------------------------------------- template Stack &Stack::operator=(Stack &rhs) { makeEmpty(); if ( rhs.isEmpty() ) return *this; const int SIZE = rhs.length(); vector tmp(SIZE); NodeType *p = rhs.myTop; int k(0); for (; k < SIZE; k++) { tmp[k] = p->info; p = p->next; } for (k = SIZE - 1; k >= 0; k--) { push(tmp[k]); } return *this; } ----------------------------------------*/ template void Stack::pop(void) { if ( !isEmpty() ) { NodeType *curr = myTop; myTop = myTop->next; delete curr; } } //*** pop template bool Stack::isEmpty(void) const { return ( myTop == NULL ); } //*** isEmpty template const T &Stack::top(void) const { return myTop->info; } template int Stack::length(void) const { NodeType *p = myTop; int count(0); while ( p != NULL ) { count++; p = p->next; } return count; } //*** length template void Stack::makeEmpty(void) { while ( !isEmpty() ) pop(); }//**** makeEmpty template void Stack::print(void) const { if ( isEmpty() ) cout << "Stack is empty\n"; else { int count(0); for ( NodeType *p = myTop; p != NULL; p = p->next) { count++; cout << setw(4) << count << ". " << p->info; } cout << endl; } } #endif //STACK_CPP