#include <iostream>
typedef int ElemType_Stack;
class Stack {
public:
ElemType_Stack* data;
int maxSize;
int top;
//默认构造函数
Stack() :data(nullptr), maxSize(0), top(0){}
//构造函数
Stack(int _maxSize) :maxSize(_maxSize), top(0) {
data = new ElemType_Stack[maxSize];
}
//拷贝构造函数
Stack(const Stack& stack) {
this->data = new ElemType_Stack[stack.maxSize];
this->maxSize = stack.maxSize;
this->top = stack.top;
for (int i = 0; i < top; i++) {
this->data[i] = stack.data[i];
}
}
//析构函数
~Stack() {
if (data != nullptr) {
delete[] data;
}
}
//判空
bool Empty() const {
return top == 0 ? true : false;
}
//进栈
bool Push(const ElemType_Stack& e) {
if (top == maxSize) {
return false;
}
data[top] = e;
top++;
return true;
}
//出栈并返回栈顶元素
bool Pop(ElemType_Stack& e) {
if (Empty()) {
return false;
}
e = data[top - 1];
top--;
return true;
}
//出栈不返回栈顶元素
bool Pop() {
if (Empty()) {
return false;
}
top--;
return true;
}
//取栈顶元素
bool GetTop(ElemType_Stack& e) const {
if (Empty()) {
return false;
}
e = data[top - 1];
return true;
}
//重载<<运算符
friend std::ostream& operator<<(std::ostream&, const Stack&);
};
std::ostream& operator<<(std::ostream& os, const Stack& stack) {
os << "[";
if (stack.top == 0) {
os << "]";
return os;
}
for (int i = stack.top - 1; i > 0; i--) {
os << stack.data[i] << ", ";
}
os << stack.data[0] << "]";
return os;
}