目录
实验环境
vscode 2022 社区版
vscode 2022 社区版的搭建:
https://blog.youkuaiyun.com/lijiamingccc/article/details/123552207
栈的存储结构
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 50
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];
int top;
}Sqstack;
栈的初始化 InitStack(Sqstack& S)
//栈的初始化
void InitStack(Sqstack& S) {
S.top = -1; //代表栈为空
}
栈判空 StackEmpty(Sqstack S)
// 栈判空
bool StackEmpty(Sqstack S) {
if (S.top == -1) {
return true;
}
else return false;
}
元素进栈 Push(Sqstack& S, ElemType x)
// 元素进栈
bool Push(Sqstack& S, ElemType x) {
if (S.top == MaxSize - 1) //栈满
return false;
S.data[++S.top] = x;
return true; //返回true表示入栈成功
}
获取栈顶元素 GetTop(Sqstack S, ElemType& m)
// 获取栈顶元素
bool GetTop(Sqstack S, ElemType& m) {
if (StackEmpty(S)) return false;
m = S.data[S.top];
return true;
}
弹出栈顶元素 Pop(Sqstack& S, ElemType& x)
bool Pop(Sqstack& S, ElemType& x) {
if (StackEmpty(S)) return false;
x = S.data[S.top--];
return true;
}
测试代码
void test_Sqstack() {
Sqstack S;
bool flag;
ElemType m;
InitStack(S);
int len, n;
printf("请输入栈元素的个数:");
scanf_s("%d", &len);
for (int i = 0; i < len; i++)
{
printf("请输入第%d个栈元素: ", i + 1);
scanf_s("%d", &n);
Push(S, n);
}
printf("栈建立完毕\n");
if (GetTop(S, m)) printf("栈顶元素为: %d\n", m);
if (Pop(S, m)) printf("弹出栈顶元素\n");
if (GetTop(S, m)) printf("当前栈顶元素为: %d", m);
}
测试结果


该博客介绍了如何使用C语言实现顺序栈的基本操作,包括初始化、判断栈空、元素入栈、获取栈顶元素和弹出栈顶元素。提供了完整的代码实现,并给出了测试代码和预期的测试结果。
1万+

被折叠的 条评论
为什么被折叠?



