顺序栈的基本操作
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define Maxsize 50
typedef int ElemType;
typedef struct
{
ElemType data[Maxsize];
int top;
}SqStack;
void InitStack(SqStack*& S)
{
S = (SqStack*)malloc(sizeof(SqStack));
S->top = 0;
}
bool StackEmpty(SqStack*& S)
{
if (S->top == 0)
{
return true;
}
else
{
return false;
}
}
bool StackFull(SqStack*& S)
{
if (S->top == Maxsize)
{
printf("栈为满\n");
return true;
}
else
{
printf("栈未满\n");
return false;
}
}
bool Push(SqStack*& S, ElemType e)
{
if (S->top == Maxsize)
{
printf("栈已满,无法进行操作\n");
return false;
}
S->data[S->top] = e;
S->top++;
return true;
}
bool Pop(SqStack*& S, ElemType& e)
{
if (S->top == 0)
{
return false;
}
S->top--;
e = S->data[S->top];
return true;
}
void GetTop(SqStack*& S, ElemType& e)
{
e = S->data[S->top - 1];
}
void DestroyStack(SqStack*& S)
{
free(S);
}
int SqStackLength(SqStack*& S)
{
return S->top;
}
void TraverseSqStack(SqStack*&S)
{
if (S->top == 0)
{
printf("栈为空,无元素在内\n");
}
else
{
printf("栈中的元素有:");
for (int i = S->top - 1; i >= 0; i--)
{
printf("%d\t",S->data[i]);
}
printf("\n");
}
}
void ClearSqStack(SqStack*& S)
{
if (S == NULL)
{
return;
}
free(S);
S->top = 0;
}
int main(int argc, char* argv[])
{
SqStack* S;
InitStack(S);
if (StackEmpty(S))
{
printf("此时栈为空\n");
}
Push(S,1);
Push(S, 2);
Push(S, 3);
Push(S, 4);
int e;
Pop(S, e);
printf("进行了一次出栈操作,原栈顶元素为%d\n",e);
GetTop(S,e);
printf("此时栈顶元素为%d\n",e);
printf("此时栈的长度为%d\n",SqStackLength(S));
TraverseSqStack(S);
ClearSqStack(S);
if (StackEmpty(S))
{
printf("此时栈为空\n");
}
return 0;
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/eaab96e7e8eb425080b39c222d328359.png#pic_center)