栈的内容相对来说比较简单:
结构体为:栈顶指针 栈底指针 栈的长度;特点:先进后出
使用顺序表(数组),来完成栈的相关操作
#include<iostream>
#include<string>
using namespace std;
#define ok 1
#define error -1
class Stack
{
public:
Stack()
{
init();
}
~Stack()
{
destory();
}
void init();
int stackempty();
int stacklength();
int gettop();
void clearstack();
void push(int val);
int pop();
void destory();
int* top;
int* base;
int stacksize = 5;
};
void Stack::init()
{
this->base = new int[stacksize]; //base 栈底
this->top = this->base;
}
int Stack::stackempty()
{
if (this->top == this->base)
{
return ok;
}
return -1;
}
int Stack::stacklength()
{
return this->top - this->base;
}
int Stack::gettop()
{
if (this->top != this->base)//非空
{
top = top - 1;
return *top;
}
return -1;
}
void Stack::clearstack()
{
top = base;
}
void Stack::push(int val)
{
*top = val;
top++;
}
int Stack::pop()
{
if (top != base) //非空
{
return(*--top);
}
return -1;
}
void Stack::destory()
{
delete this->base;
this->base = NULL; // 指向空
this->top = NULL;
}