目录
栈的应用![](https://img-blog.csdnimg.cn/dca284b2a7fa4ddd8356c48a3892f1cb.png)
栈的基本概念
栈的操作实现
栈类
#include<iostream>
using namespace std;
#define maxsize 1000
typedef int elemtype;
class Sqstack {
public:
static Sqstack* get()
{
static Sqstack a;
return &a;
}
public:
void initstack();
void destroystack();
bool push(elemtype in);
bool pop();
elemtype gettop();
private:
elemtype* base;//栈底
elemtype* top;//栈顶
elemtype stacksize;//栈容量
};
初始化栈
void Sqstack::initstack()//初始化栈
{
this->base = new int[maxsize];
if (this->base == NULL)
exit(0);
this->top = this->base;
this->stacksize = maxsize;
}
删除栈
void Sqstack::destroystack()//删除栈
{
if (this->base) {
delete this->base;
this->stacksize = 0;
this->base = this->top = NULL;
}
else {
cout << "栈不存在";
}
}
压入栈
bool Sqstack::push(elemtype in) //压入元素
{
if (this->top - this->base < this->stacksize)
{
*(this->top) = in;
this->top++;
this->stacksize++;
return 1;
}
else
return 0;
}
弹出栈
bool Sqstack::pop()//弹出元素
{
if (this->top - this->base)
{
this->top--;
*(this->top) = 0;
return 1;
}
return 0;
}
取栈顶元素
elemtype Sqstack::gettop()//取栈顶元素
{
if (this->top - this->base)
return *(this->top - 1);
}