//stack.h定义
#include<iostream>
#include<cassert>
#ifndef STACK
#define STACK
template<class T>
class stack{
int top;
T *a;
int cn;
public:
stack(int c);
~stack();
bool empty()const;
bool full()const;
void push(const T &item);
T gettop()const;
void pop();
void clear();
void display(const stack<T> &s1);
};
template<class T>//初始化栈,栈顶top=-1
stack<T>::stack(int c){
assert(c > 0);
cn = c;
a = new T[cn];//动态数组建立
if (a!= 0)
top = -1;
else
assert(a != 0);
}
template<class T>//析构函数调用清除动态数组
stack<T>::~stack(){
delete[]a;
}
template<class T>//判空,top=-1则为空
bool stack<T>::empty()const{
return(top == -1);
}
template<class T>//栈满判断
bool stack<T>::full()const{
return(top == cn - 1);
}
template<class T>//压栈,首先判断是否栈满
void stack<T>::push(const T &item){
assert(!full());
a[++top] = item;//压栈
}
template<class T>//取栈顶元素
T stack<T>::gettop()const{
assert(!empty());
return a[top];
}
template<class T>//弹栈
void stack<T>::pop(){
assert(!empty());
return a[top--];
}
template<class T>//清除栈
void stack<T>::clear(){
top = -1;
}
template<class T>//栈显示,从栈顶到栈底
void stack<T>::display(const stack<T> &s1){
for (int i = cn-1; i >= 0; i--)
cout << s1.a[i] << " " << endl;
}
#endif
//main函数测试
#include<iostream>
#include"stack.h"
using namespace std;
int main(){
stack<int>s(3);
cout << "stack is empty?" << s.empty() << endl;
s.push(1);
s.push(2);
s.push(3);
cout << "the stack is:" << endl;
s.display(s);
cout << "the top is:" << s.gettop() << endl;;
s.clear();
stack<char>a(3);
a.push('x');
a.push('u');
a.push('z');
a.display(a);
system("pause");
return 0;
}