1.定义栈的结构
typedef struct
{
ElemType data[Maxsize];
int top;
}SqStack;
2.栈的初始化
void InitStack(SqStack& S)
{
for (int i = 0; i < Maxsize; i++)
S.data[i] = 0;
S.top = -1;
}
3.判断栈空
Status StackEmpty(SqStack S)
{
if (S.top == -1)
{
return true;
}
else
{
return false;
}
}
4.入栈
Status Push(SqStack& S, ElemType x)
{
if (S.top == Maxsize - 1)
return false;
S.top = S.top + 1;
S.data[S.top] = x;
return true;
}
5.出栈
Status Pop(SqStack& S, ElemType& x)
{
if (S.top == -1)
return false;
x = S.data[S.top];
S.top = S.top - 1;
return true;
}
6.读栈顶
ElemType GetTop(SqStack& S, ElemType& x)
{
if (S.top == -1)
return false;
x = S.data[S.top];
return true;
}
全部代码
#include<stdio.h>
#include<stdlib.h>
#define Maxsize 20
typedef int ElemType;
typedef bool Status;
typedef struct
{
ElemType data[Maxsize];
int top;
}SqStack;
void InitStack(SqStack& S)
{
for (int i = 0; i < Maxsize; i++)
S.data[i] = 0;
S.top = -1;
}
Status StackEmpty(SqStack S)
{
if (S.top == -1)
{
return true;
}
else
{
return false;
}
}
Status Push(SqStack& S, ElemType x)
{
if (S.top == Maxsize - 1)
return false;
S.top = S.top + 1;
S.data[S.top] = x;
return true;
}
Status Pop(SqStack& S, ElemType& x)
{
if (S.top == -1)
return false;
x = S.data[S.top];
S.top = S.top - 1;
return true;
}
ElemType GetTop(SqStack& S, ElemType& x)
{
if (S.top == -1)
return false;
x = S.data[S.top];
return true;
}
int main()
{
SqStack S;
ElemType x;
InitStack(S);
Push(S, 6);
Push(S, 9);
Pop(S, x);
GetTop(S, x);
if (StackEmpty)
{
printf("栈不为空\n");
}
else
{
printf("栈为空\n");
}
printf("%d", x);
return 0;
}