templateThere is no implementation of the isFull() method as we are using the STL list class and the only way for the stack to be full is if the program is out og memory. We should handle this using exceptions. The stack pointer is hidden as the list pointer in the stk object.class stack { public: void push(TYPE x) { stk.push_front(x);} TYPE pop() { TYPE x = stk.front(); stk.pop_front(); return x;} int size() { return stk.size();} bool isEmpty() { return stk.empty();} friend ostream & operator<<(ostream & os, stack & s) { list ::iterator ptr = s.stk.begin(); while(ptr != s.stk.end()) os << *ptr++ << ' '; os << endl; return os; } private: list stk; };
Here is a simple main that uses the template above to make a stack of integers.
int main(int argc, char* argv[]) { stackThe output looks likeS; int i; if(S.isEmpty()) cout << "Stack is initially empty" << endl; else cout << "Stack is initially NOT empty" << endl; for(i=0; i< 10; i++) S.push(i); if(S.isEmpty()) cout << "Stack is empty after push loop" << endl; else cout << "Stack is NOT empty after push loop" << endl; cout << "stack contents using operator<<()" << endl; cout << S << endl; cout << "Size of stack before pop loop is " << S.size() << endl; cout << "stack contents using pop()" << endl; while(! S.isEmpty()) { cout << S.pop() << ' '; } // while cout << endl; cout << "Size of stack after pop loop is " << S.size() << endl; return 0; }
Stack is initially empty Stack is NOT empty after push loop stack contents using operator<<() 9 8 7 6 5 4 3 2 1 0 Size of stack before pop loop is 10 stack contents using pop() 9 8 7 6 5 4 3 2 1 0 Size of stack after pop loop is 0 Press any key to continue