顺序存储方式2:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 128
typedef int ElemType;
typedef struct _SqStack
{
int top;
ElemType* base;
}SqStack;
//初始化栈
bool initStack(SqStack& S)
{
S.base = new ElemType[MAX_SIZE];
if (!S.base) return false;
S.top = 0;
return true;
}
//判断栈是否为空
bool isEmpty(SqStack& S)
{
if (S.top == 0) return true;
return false;
}
//判断是否为满
bool isFull(SqStack& S)
{
if (S.top == MAX_SIZE) return true;
return false;
}
//压栈
bool pushStack(SqStack& S, ElemType elem)
{
if (isFull(S)) return false;
S.base[S.top++] = elem;
return true;
}
//出栈
bool popStack(SqStack& S, ElemType& elem)
{
if (isEmpty(S)) return false;
elem = S.base[--S.top];
return true;
}
//取栈顶
bool getTop(SqStack& S, ElemType& elem)
{
if (isEmpty(S)) return false;
elem = S.base[S.top - 1];
return true;
}
//元素个数
int getSize(SqStack& S)
{
return S.top;
}
//销魂栈
void destoryStack(SqStack& S)
{
if (S.base)
{
delete S.base;
S.base = NULL;
}
S.top = 0;
}
int main()
{
SqStack S;
ElemType elem=-1;
if (initStack(S))
printf("栈初始化成功,开始压栈...\n");
for (int i = 0; i < 6; i++)
{
if (pushStack(S, i + 10))
printf("元素[%d],成功压栈\n", i + 10);
}
printf("元素个数:%d\n", getSize(S));
for (int i = 0; i < 6; i++)
{
if (popStack(S, elem))
printf("元素[%d],成功出栈\n", elem);
}
printf("元素个数:%d\n", getSize(S));
destoryStack(S);
system("pause");
return 0;
}