#include<iostream>
using namespace std;
/*
栈:先进后出、后进向出,仅在表尾i而进行插入和删除操作的线性表。主要分为顺序栈(数组)、链栈(链表)
*/
class stack
{
private:
int *date;
int top; //top记录入栈元素的位置。top=0,表示入栈1个元素。top=-1表示空栈。top=size-1表示满栈
const int size = 100;
public:
stack():top(-1), date(new int[size]){} //构造函数-栈的初始化
//入栈
void push(const int &elm);
//出栈
void pop();
//返回栈中的元素个数
int stackLength();
//若栈存在且非空,返回栈顶元素
int GetTop();
//若栈存在,则将栈清空
void ClearStack();
//判断栈是否为空
bool isempty();
//判断栈是否为满
bool isFull();
//遍历栈
void ReadStack();
~stack();
};
stack::~stack()
{
if(date != nullptr)
{
delete[] date;
date = nullptr;
}
}
void stack::push(const int &elm)
{
//检查是否满栈,若满栈,则入栈错误,若没满,则执行插入
if(isFull())
{
cout << "该栈已满" << endl;
exit(0);
}
else
{
this->date[++top] = elm;
}
}
void stack::pop()
{
//判断该栈是否为空
if(isempty())
{
cout << "空栈,无元素可出栈" << endl;
}
else
{
--this->top;
}
}
int stack::stackLength()
{
return this->top + 1;
}
int stack::GetTop()
{
if (isempty())
{
cout << "空栈,栈顶无元素" << endl;
return 0;
}
return this->date[top];
}
void stack::ClearStack()
{
if (isempty())
{
cout << "空栈,无元素可清除" << endl;
}
else
{
this->top = -1;
}
}
bool stack::isempty()
{
return this->top == -1;
}
bool stack::isFull()
{
return this->top == size - 1;
}
void stack::ReadStack()
{
if (isempty())
{
cout << "空栈,无元素遍历" << endl;
}
else
{
for(int i = 0; i <= this->top; ++i)
{
cout << this->date[i] << " ";
}
}
}
void test()
{
stack *s = new stack();
s->push(1);
s->push(2);
s->push(3);
s->push(4);
s->push(5);
s->pop();
s->ReadStack();
cout << endl;
cout << s->stackLength() << s->GetTop() << endl;
}
int main()
{
test();
return 0;
}
输出:
1 2 3 4
44