一、采用顺序存储结构实现栈(即顺序栈)
总结:

Stack.h
cpp
#pragma once
#include<stdio.h>
#include<stdbool.h>
#define MaxSize 10
typedef int ElemType;
// 采用顺序结构实现栈
// 定义栈的结构
typedef struct SqStack
{
ElemType arr[MaxSize]; // 栈中最多可以存储MaxSize个ElemType类型的数据
int top; // top是栈顶指针,指向栈顶元素
}SqStack;
// 栈的初始化
void Init(SqStack& S);
// 判断栈是否为空。为空返回true,否则返回false。
bool Empty(SqStack S);
// 新元素x入栈
bool Push(SqStack& S, ElemType x);
// 删除栈顶元素(出栈操作),并将栈顶元素的值赋给变量e
bool Pop(SqStack& S, ElemType& e);
// 获取栈顶元素,并将栈顶元素的值赋给变量e
bool GetTop(SqStack S, ElemType& e);
Stack.cpp
cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include"Stack.h"
// 栈的初始化
void Init(SqStack& S)
{
S.top = -1;
}
// 判断栈是否为空。为空返回true,否则返回false
bool Empty(SqStack S)
{
if (S.top == -1)
return true; // 栈为空
else
return false; // 栈不为空
}
// 新元素x入栈
bool Push(SqStack& S, ElemType x)
{
if (S.top == MaxSize - 1) // 此时表示栈中已经存满了元素,无法执行入栈操作
return false;
S.top++;
S.arr[S.top] = x; // 将新元素x放到栈顶的位置
return true;
}
// 删除栈顶元素(出栈操作),并将栈顶元素的值赋给变量e
bool Pop(SqStack& S, ElemType& e)
{
if (S.top == -1) // 表示此时栈为空,无法执行出栈操作
return false;
e = S.arr[S.top]; // 将栈顶元素赋给e
S.top--;
return true;
}
// 获取栈顶元素,并将栈顶元素的值赋给变量e
bool GetTop(SqStack S, ElemType& e)
{
if (S.top = -1)
return false; // 表示栈为空,无法指向获取栈顶元素的操作
e = S.arr[S.top];
return true;
}
二、共享栈
共享栈就是两个栈共享同一片空间
cpp
// 定义共享栈的结构(两个栈共享同一块内存,这两个栈分别命名为0号栈与1号栈)
# define MaxSize 10
typedef int ElmeType;
typedef struct ShStack {
ElmeType data[MaxSize];
int top0; // 0号栈的栈顶指针
int top1; // 1号栈的栈顶指针
}ShStack;
// 共享栈的初始化
void InitStack(ShStack& S)
{
S.top0 = 0;
S.top1 = MaxSize;
}
// 共享栈满了的条件:S.top0+1 == S.top1