首先是顺序栈的模块说明
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int SElemType;
typedef int Status;
typedef struct {
SElemType* base;
SElemType* top;
int stacksize;
}SqStack;
初始化
Status CreateStack(SqStack& S)
{
S.base = (SElemType*)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if (!S.base)return 0;
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return 1;
}
判断是否为空
bool StackEmpty(SqStack& S)
{
return S.top == S.base;
}
销毁
Status DestroyStack(SqStack& S)
{
if (!S.base)return 0;
free(S.base);
S.base = S.top = NULL;
S.stacksize = 0;
return 1;
}
得到栈的长度
int StackLength(SqStack& S)
{
return S.top - S.base;
}
进栈(Push)
Status Push(SqStack& S, SElemType e)
{
if (S.top - S.base >= S.stacksize)
{
S.base = (SElemType*)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemType));
if (!S.base)return 0;
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
return 1;
}
出栈(Pop)
Status Pop(SqStack& S, SElemType& e)
{
if (S.top == S.base)return 0;
e = *--S.top;
return 1;
}
得到栈顶元素
Status GetTop(SqStack& S, SElemType& e)
{
if (S.top == S.base)return 0;
e = *(S.top - 1);
return 1;
}
9,总代码
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int SElemType;
typedef int Status;
typedef struct {
SElemType* base;
SElemType* top;
int stacksize;
}SqStack;
Status CreateStack(SqStack& S)
{
S.base = (SElemType*)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if (!S.base)return 0;
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return 1;
}
Status DestroyStack(SqStack& S)
{
if (!S.base)return 0;
free(S.base);
S.base = S.top = NULL;
S.stacksize = 0;
return 1;
}
bool StackEmpty(SqStack& S)
{
return S.top == S.base;
}
int StackLength(SqStack& S)
{
return S.top - S.base;
}
Status GetTop(SqStack& S, SElemType& e)
{
if (S.top == S.base)return 0;
e = *(S.top - 1);
return 1;
}
Status Push(SqStack& S, SElemType e)
{
if (S.top - S.base >= S.stacksize)
{
S.base = (SElemType*)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemType));
if (!S.base)return 0;
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
return 1;
}
Status Pop(SqStack& S, SElemType& e)
{
if (S.top == S.base)return 0;
e = *--S.top;
return 1;
}
int main()
{
SElemType e;
SqStack S;
CreateStack(S);
printf("IEmpty?:%d\n", StackEmpty(S));
for (int i = 1; i <= 5; i++)
{
Push(S, i);
for (int* p = S.base; p < S.top; p++)
{
printf("%d ", *p);
}
printf("\n");
}
printf("After Pop:\n");
Pop(S,e);
printf("length:%d\n", StackLength(S));
printf("After GetPop:\n");
GetTop(S, e);
printf("length:%d\n", StackLength(S));
printf("Top:%d\n", e);
for (int* p = S.base; p < S.top; p++)
{
printf("%d ", *p);
}
printf("\nlength:%d\n",StackLength(S));
printf("IEmpty?:%d\n", StackEmpty(S));
DestroyStack(S);
return 0;
}