一个简单的实现例子,初始化26个英文字母。

#include <iostream> 
using namespace std;
template <typename T>
class Stack{
public:
Stack(int max=100);
~Stack(){delete[] stk;}
bool empty()const {return stk_top==-1;}
bool full()const {return stk_top==max_top;}
int size()const {return stk_top+1;}
T top()const; //显示栈顶元素
Stack<T>& push(const T& x); //x元素入栈
Stack<T>& pop(T& x); //出栈并返回元素x
private:
int stk_top; //栈顶位置
int max_top; //栈顶位置的最大值
T *stk; //栈元素数组
};
template <typename T>
Stack<T>::Stack(int max)
{
max_top=max-1;
stk=new T[max];
stk_top=-1;
}
template <typename T>
T Stack<T>::top()const
{
if (!empty()) return stk[stk_top];
}
template <typename T>
Stack<T>& Stack<T>::push(const T& x)
{
stk[++stk_top]=x;//先移动栈顶位置再赋值
return *this;
}
template <typename T>
Stack<T>& Stack<T>::pop(T& x)
{
x=stk[stk_top--];//先赋值再移动栈顶位置
return *this;
}
int main()
{
char s1,s2;
s1='A';
s2='Z';
Stack<char> stack;
for(int i=s2;i>=s1;i--)
stack.push(i);
char x;
while(!stack.empty())
{
stack.pop(x);
cout <<x <<" ";
}
return 0;
}