一头进出,先进后出
定义栈的类模板
template <typename Type>
class Stack {
private:
Type* stk;
int top;
int MAXN;
public:
Stack(int size);
~Stack();
int push(Type x);
int pop(Type* px);
Type getTop();
int isEmpty()const;
int isFull()const;
int size()const;
};
函数实现
template <typename Type>
Stack<Type>::Stack(int size) {
MAXN = size;
stk = new Type[MAXN];
top = -1;
}
template <typename Type>
Stack<Type>::~Stack() {
delete stk;
}
template <typename Type>
int Stack<Type>::push(Type x) {
if (top >= MAXN - 1)return -1;
stk[top] = x;
top++;
return 0;
}
template <typename Type>
int Stack<Type>::pop(Type* x) {
if (top == -1)return 0;
*x = stk[top];
top--;
}
template <typename Type>
Type Stack<Type>::getTop() {
if (top == -1)return NULL;
return stk[top];
}
template <typename Type>
int Stack<Type>::isEmpty()const {
return top == -1;
}
template <typename Type>
int Stack<Type>::isFull()const {
return top == MAXN - 1;
}
template <typename Type>
int Stack<Type>::size() const {
return top;
}
测试
int main()
{
Stack<int> s(20);
cout << "是否为空栈" << s.isEmpty() << endl;
s.push(1);
cout << "1入栈" << endl;
s.push(5);
cout << "5入栈" << endl;
s.push(10);
cout << "10入栈" << endl;
cout << "栈的大小" << s.size() << endl;
int x = 0;
s.pop(&x);
cout << "删除的元素" << x << endl;
cout << "删除一个元素后栈的大小" << s.size() << endl;
cout << "栈顶元素" << s.getTop() << endl;
}