typedef int SElemType;
typedef struct {
SElemType data[MAXSIZE];
int top;//栈顶指针
}Sqstack;
1、初始化
//初始化
bool InitStack(Sqstack* S) {
S->top = -1;
return true;
}
2、判断栈是否为空
//判断栈是否为空
bool StackEmpty(Sqstack S) {
if (S.top == -1) {
return true;
}
else {
return false;
}
}
3、进栈
//进栈
bool Push(Sqstack* S, SElemType X) {
if (S->top == MAXSIZE - 1) {
return false;
}
else {
S->top = S->top + 1;
S->data[S->top] = X;
return true;
}
}
4、出栈
//出栈
bool Pop(Sqstack* S, SElemType* e) {
if (S->top == -1) {
return false;
}
else {
*e = S->data[S->top];
S->top--;
return true;
}
}
5、读取栈顶元素
//读取栈顶元素
bool GetTop(Sqstack S, SElemType* e) {
if (S.top == -1) {
return false;
}
else {
*e = S.data[S.top];
return true;
}
}
6、求栈的长度
//求栈的长度
int StackLength(Sqstack S)
{
return S.top + 1;
}
7、展示
//展示
void DisStack(Sqstack S) {
int i = 0;
while (i <= S.top) {
printf("%d ", S.data[i]);
i++;
}
printf("\n");
}
8、完整+测试程序
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdbool.h>
#define MAXSIZE 10
typedef int SElemType;
typedef struct {
SElemType data[MAXSIZE];
int top;//栈顶指针
}Sqstack;
//初始化
bool InitStack(Sqstack* S) {
S->top = -1;
return true;
}
//判断栈是否为空
bool StackEmpty(Sqstack S) {
if (S.top == -1) {
return true;
}
else {
return false;
}
}
//进栈
bool Push(Sqstack* S, SElemType X) {
if (S->top == MAXSIZE - 1) {
return false;
}
else {
S->top = S->top + 1;
S->data[S->top] = X;
return true;
}
}
//出栈
bool Pop(Sqstack* S, SElemType* e) {
if (S->top == -1) {
return false;
}
else {
*e = S->data[S->top];
S->top--;
return true;
}
}
//读取栈顶元素
bool GetTop(Sqstack S, SElemType* e) {
if (S.top == -1) {
return false;
}
else {
*e = S.data[S.top];
return true;
}
}
//求栈的长度
int StackLength(Sqstack S)
{
return S.top + 1;
}
//展示
void DisStack(Sqstack S) {
int i = 0;
while (i <= S.top) {
printf("%d ", S.data[i]);
i++;
}
printf("\n");
}
//TEST
int main(void) {
Sqstack S;
int e;
int flag = InitStack(&S);//初始化
if (flag) {
for (int i = 1; i <= MAXSIZE; i++) {
Push(&S, i);//进栈
}
}
printf("栈中元素依次为:");
DisStack(S);//输出
Pop(&S, &e);
printf("弹出的栈顶元素为%d\n", e);//9
GetTop(S, &e);
printf("栈顶元素为%d 栈的长度为%d\n", e, StackLength(S));
printf("栈中元素依次为:");
DisStack(S);//输出
return 0;
}