#include <iostream>
using namespace std;template <typename T>
class stack{private:int top; //栈顶指针int maxLen; //栈最大长度T *data; //用数组来创建栈public:stack(int top_ = -1 , int maxLen_ = 10):top(top_),maxLen(maxLen_){data = new T[maxLen]; //长度为maxLen的动态数组}~stack(){delete [] data; //释放动态数组}void Push(T x); //将x推进栈void Pop(); //推出栈顶元素T getPeek(); //读栈顶元素bool isEmpty(); //判断栈是否为空bool isFull(); //判断栈是否满void printAll(); //打印整个栈
};template <typename T>
void stack<T>::Push(T x){ //将x推进栈,实现部分if(isFull())return;top++;data[top] = x;
}template <typename T>
void stack<T>::Pop(){ //推出栈顶元素,实现部分if(isEmpty())return;top--;
}template <typename T>
T stack<T>::getPeek(){ //获得栈顶元素,实现部分if(isEmpty())return;return data[top];
}template <typename T>
bool stack<T>::isEmpty(){ //判断栈是否为空,实现部分return top==-1;
}template <typename T>
bool stack<T>::isFull(){ //判断栈是否满,实现部分return top==maxLen-1;
}template <typename T>
void stack<T>::printAll(){ //打印栈内元素,实现部分if(isEmpty())return;for(int i = 0; i <=top ; i++){cout<<data[i]<<endl;}
}
void main(){stack<int> a; //创建元素类型为int的栈对象a.Push(1); //将1推进栈a.Push(2); //将2推进栈a.Push(3); //将3推进栈a.Push(4); //将4推进栈a.Push(5); //将5推进栈a.Pop(); //弹出栈顶元素a.printAll(); //打印栈内元素
}
转载于:https://www.cnblogs.com/xiaogua918/p/4181589.html