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");
}
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);
GetTop(S, &e);
printf("栈顶元素为%d 栈的长度为%d\n", e, StackLength(S));
printf("栈中元素依次为:");
DisStack(S);
return 0;
}
|