链接: 王道2021数据结构链接
提取码:rpy8
–来自百度网盘超级会员V4的分享`
//首先要注意的一点是,这种方法的栈顶指针指的栈顶元素的那一块
//还有一种是栈顶指针指向即将插入数据的那一块
#include <stdio.h>
#include <stdlib.h>
//定义栈中元素的最大个数
#define MaxSize 10
typedef ElemType int;
typedef struct{
//静态数组存放栈中元素
ElemType data[MaxSize];
//栈顶指针
int top;
}SqStack;
//初始化栈 02 02:30
void InitStack(SqStack &S){
//栈顶指针设置为-1(-1的意思是栈顶指针没有指向任何东西)
S.top = -1;
}
//判断栈空 02 02:30
bool StackEmpty(SqStack S){
//看栈顶指针是否为-1
return (S.top == -1);
}
/*--------------------------------------------------*/
//新元素入栈 02 03:02
bool Push(SqStack &S, ElemType x){
//先判断是否栈满 栈顶指针为MaxSize-1
if(S.top == MaxSize - 1) return false;
//栈顶指针加一
S.top++;
//新元素入栈
S.data[S.top] = x;
//返回
return true;
}
/*--------------------------------------------------*/
//出栈操作 02 05:52
bool Pop(SqStack &S, ElemType &x){
//先判断栈是否为空 看栈顶指针是否为-1
if(S.top = -1) return false;
//栈顶元素先出栈(就是将该元素赋值给x)
x = S.top;
//将栈顶指针的值-1
S.top--;
//返回
return true;
}
/*--------------------------------------------------*/
//读栈顶元素
bool GetTop(SqStack S, ElemType &x){
//先判断栈是否为空
if(S.top = -1) return false;
//x记录栈顶元素
x = S.data[S.top];
//返回
return true;
}
void testStack(){
SqStack S;
InitStack(S);
}