栈类模板¶
约 4 个字 43 行代码 预计阅读时间 1 分钟
#include <iostream>
using namespace std;
template<class T>
class Stack{
private:
T * arr;
int top;
int capacity;
public:
Stack(int size):top(-1),capacity(size){
arr = new T[size];
}
~Stack(){
delete [] arr;
}
void push(T value){
if(top == capacity - 1){
cout << "stack overflow" << endl;
}
else {
arr[++top] = value;
}
}
T pop(){
if(top == -1){
cout << "stack underflow" << endl;
return T();
}
else return arr[top--];
}
bool isEmpty(){
return top == -1;
}
};
int main(){
Stack<int> stack(5);
stack.push(50);
stack.push(60);
cout << stack.pop() << " " << stack.pop() << endl;
}