1 #include <iostream>
2 template<class Type>
3 class Stack
4 {
5 public:
6 Stack(int MaxStackSize=100);
7 bool IsFull();
8 bool IsEmpty();
9 void StackFull();
10 void StackEmpty();
11 void Push(const Type& x);
12 Type Pop(Type& x);
13 private:
14 int top;
15 Type * stack;
16 int MaxSize;
17 };
18 template<class Type>
19 Stack<Type>::Stack(int MaxStackSize):MaxSize(MaxStackSize)//构造函数
20 {
21 stack = new Type[MaxSize];
22 top = -1;
23 }
24 template<class Type>
25 inline bool Stack<Type>::IsFull()//判断栈满
26 {
27 if(top == MaxSize-1) return true;
28 else return false;
29 }
30 template<class Type>
31 inline bool Stack<Type>::IsEmpty()//判断栈空
32 {
33 if(top == -1) return true;
34 else return false;
35 }
36 template<class Type>
37 void Stack<Type>::StackFull()
38 {
39 std::cout<<"StackFull,PushFail\n";
40 }
41 template<class Type>
42 void Stack<Type>::StackEmpty()
43 {
44 std::cout<<"StackEmpty,PopFail\n";
45 }
46 template<class Type>
47 void Stack<Type>::Push(const Type& x)//入栈
48 {
49 if(IsFull()) StackFull();
50 else stack[++top] = x;
51 }
52 template<class Type>
53 Type Stack<Type>::Pop(Type& x)//出栈
54 {
55 if(IsEmpty())
56 {
57 StackEmpty();
58 return -1;
59 }
60 x = stack[top--];
61 return x;
62 }
63 int main(int argc, char** argv)//测试代码
64 {
65 Stack<int> S(100);//实例化空间大小为100的栈
66 for(int i=0;i<10;i++)
67 S.Push(i);//将从0-9的数入栈
68 int tmp;
69 while(!S.IsEmpty())//出栈
70 {
71 std::cout<<S.Pop(tmp)<<std::endl;
72 }
73 std::cout<<S.Pop(tmp)<<std::endl;
74 return 0;
75 }