頭文件
#include<stdio.h>
#include<stdlib.h>
抽象數據類型
typedef struct {
ElemType data[MaxSize];
int top;
}SqStack;
初始化棧
void InitStack(SqStack &S)
{
S.top = -1;
}
判斷棧是否爲空
bool StackEmpty(SqStack& S)
{
if (S.top == -1)
return true;
else
return false;
}
入棧操作
bool Push(SqStack& S, ElemType x)
{
if (S.top == MaxSize - 1)
{
return false;
}
S.data[++S.top] = x;
return true;
}
出棧操作
bool Pop(SqStack& S, ElemType& x)
{
if (-1 == S.top)
return false;
x = S.data[S.top];
return true;
}
取棧頂元素
bool GetTop(SqStack& S, ElemType& x)
{
if (-1 == S.top)
return false;
x = S.data[S.top];
return true;
}
獲得棧中元素個數
int LengthStack(SqStack S)
{
return ++S.top;
}
打印棧元素(從棧頂到棧尾)
void PrintStack(SqStack& S)
{
printf("從棧頂到棧底元素分別是:");
for (int i = S.top; i >= 0; i--)
{
printf("%d ", S.data[i]);
}
printf("\n");
}
測試代碼
int main()
{
SqStack S;
bool flag;
ElemType m;
InitStack(S);
Push(S, 1);
Push(S, 2);
Push(S, 3);
PrintStack(S);
printf("當前棧元素個數爲:%d\n", LengthStack(S));
Push(S, 4);
Push(S, 5);
printf("當前棧元素個數爲:%d", LengthStack(S));
}