// 顺序栈
constexpr int MAXSIZE = 10;
using ElemType = int;
typedef struct {
ElemType data[MAXSIZE];
int top;
}SqStack;
// 初始化栈
void InitStack(SqStack &S)
{
s.top = -1; // 初始化栈顶指针,指向栈顶元素,栈空时为-1
}
// 判断栈是否为空
bool StackEmpty(SqStack S)
{
return S.top == -1;
}
// 新元素入栈
bool Push(SqStack &S, ElemType x)// 入栈需要首先判满
{
if (S.top == MAXSIZE - 1) {
return false;
}
S.data[++S.top] = x;
return true;
}
// 出栈
bool Pop(SqStack &S, ElemType &x)// 出栈首先判空
{
if (S.top == -1) {
return false;
}
S.data[S.top--];
return true;
}
bool GetTop(SqStack S, ElemType &x)// 获取栈顶先判空
{
if (S.top == -1) {
return false;
}
x = S.data[S.top];
return true;
}
// 共享栈
typedef struct {
ElemType data[MAXSIZE];
int top0;
int top1;
}ShStack;
void InitShStack(ShStack &S)
{
S.top0 = -1;
S.top1 = MAXSIZE;
}
// 链栈
typedef struct Linknode {
ElemType data;
Linknode* next;
Linknode(int data) : data(data), next(nullptr) {}
} Linknode, *LiStack;
// 初始化链栈
bool InitLiStack(LiStack &S)
{
// S = (Linknode*)malloc(Linknode);
// if (S = nullptr) {
// return false;
// }
// S->next = nullptr;
S = new Linknode(-1);// 头结点存放无效数据-1,next指针初始化为空
}
// 判断链栈是否为空
bool LiStackEmpty(LiStack S)
{
return S->next == nullptr;
}
// 新元素入栈
bool Push(LiStack &S, ElemType x)// 头插法入栈,头出栈,链栈入栈不需要判满
{
Linknode* s = new Linknode(x);
if (s == nullptr) {
return false;
}
s->next = S->next;
S->next = s;
return true;
}
bool Pop(LiStack& S, ElemType& x)链栈出栈也要先判空
{
if (S->next == nullptr) {
return false;
}
Linknode* s = S->next;
x = s->data;
S->next = s->next;
delete s;
return true;
}
24王道栈代码合集
最新推荐文章于 2024-05-28 21:51:03 发布