//Stack.h
#define NULL 0 #include <iostream> using namespace std; template <class Type> class Stack { public: Stack() { top=NULL; } ~Stack() { struct node *temp; while (top) { temp=top; top=top->link; delete temp; } } bool Push(const Type item); bool Pop(Type &item); inline bool StackEmpty() { if (top) { return false; } else { return true; } } private: struct node { Type data; struct node *link; }; struct node *top; }; template <class Type> bool Stack::Push(const Type item) { struct node *temp = new node; if (temp) { temp->data = item; temp->link = top; top = temp; return true; } else { cout<<"Out of space !"<<endl; return false; } } template <class Type> bool Stack::Pop(Type &item) { if (StackEmpty()) { cout<<"The stack is empty"<<endl; return false; } struct node *temp; item = top->data; temp = top; top = top->link; delete temp; return true; }
//main.cpp
#include <iostream> #include "Stack.h" using namespace std; void main() { int i,item; Stack <int> S; for (i=0;i<4;i++) { S.Push(i); cout<<i<<" "; } cout<<endl; for (i=0;i<4;i++) { S.Pop(item); cout<<item<<" "; } }