📄 stack.h
字号:
#include<stdlib.h>
enum Error_code{success,overflow,underflow};
template<class T>
class Stack{
public:
Stack(int n=20);
Stack(const Stack<T>& S); //拷贝构造函数
~Stack();
Error_code pop(); //弹出(删除)栈顶元素
Error_code top(T&); //取栈顶元素
Error_code push(T&); //将数据压入栈中
void operator=(const Stack<T>&); //重载赋值运算符
int ele_numbers(){return counter;}; //返回元素个数
void clear(){counter=0;} //将栈清0
bool empty(); //栈空则返回true,否则返回false
bool full(); //栈满则返回true,否则返回false
private:
int counter; //当前堆栈元素个数
int MaxSize; //最大元素个数
T* stack;
};
template<class T>
Stack<T>::Stack(int n){ //栈初始化
counter=0;
MaxSize=n;
stack=new T[MaxSize];
if(!stack){ //若stack为空则表明内存不足
cout<<"NO ENOUGH MEMORY!";
exit(1);
}
return;
}
template<class T>
Stack<T>::Stack(const Stack<T>& S){ //拷贝构造函数
counter=S.counter;
MaxSize=S.MaxSize;
stack=new T[MaxSize];
if(!stack){
cout<<"NO ENOUGH MEMORY!";
exit(1);
}
for(int i=0;i<counter;++i) //元素逐个复制
stack[i]=S.stack[i];
return;
}
template<class T>
Stack<T>::~Stack(){
delete []stack;
return;
}
template<class T>
Error_code Stack<T>::pop(){
if(empty())return underflow; //栈空的情形
--counter; //将顶元素删去
return success;
}
template<class T>
Error_code Stack<T>::top(T& e){
if(empty())return underflow; //若栈空时
e=stack[counter-1]; //用e返回栈顶元素
return success;
}
template<class T>
Error_code Stack<T>::push(T& e){
if(full())return overflow; //栈满的情形
stack[counter++]=e;
return success;
}
template<class T>
void Stack<T>::operator=(const Stack<T>& another){ //赋值重载
counter=another.counter;
MaxSize=another.MaxSize;
if(!stack) delete []stack; //将原来的栈删去
stack=new T[MaxSize];
if(!stack){
cout<<"NO ENOUGH MEMORY!";
exit(1);
}
for(int i=0;i<counter;++i) //元素逐个复制
stack[i]=another.stack[i];
return;
}
template<class T>
bool Stack<T>::empty(){
return counter==0;
}
template<class T>
bool Stack<T>::full(){
return counter==MaxSize;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -