/****************************************************************************************************************
程序:栈的顺序实现
作者:小单
完成时间:2013年4月24
*****************************************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define TRUE 1
#define FALSE 0
#define STACK_INIT_SIZE 100 //存储空间初始化分配量
#define STACKINCREMENT 10
typedef int Status;
typedef int SElemType;
typedef struct
{
SElemType *base; //在栈构造之前和销毁之后,base的值为NULL
SElemType *top; //栈顶指针
int stackSize; //当前已分配的存储空间
}SqStack;
Status InitStack(SqStack &S)
{
//构造一个空栈
S.base = (SElemType *)malloc(sizeof(SElemType) * STACK_INIT_SIZE);
if(!S.base)
exit(OVERFLOW);
S.top = S.base;
S.stackSize = STACK_INIT_SIZE;
return OK;
}
Status DestroyStack(SqStack &S)
{
//销毁栈
if(S.base == S.top)
return ERROR;
free(S.base);
S.base = NULL;
S.top = NULL;
return OK;
}
Status ClearStack(SqStack &S)
{
//清空栈
S.top = S.base;
S.stackSize = 0;
return OK;
}
Status StackEmpty(const SqStack &S)
{
//判断栈是否为空
if(S.top == S.base)
return TRUE; //栈空
return FALSE;
}
int StackLength(const SqStack &S)
{
//返回S的元素个数
return S.top - S.base;
}
Status GetTop(const SqStack &S, SElemType &e)
{
//返回栈顶元素
if(S.top == S.base)
return ERROR;
e = *(S.top - 1);
return OK;
}
Status Push(SqStack &S, const SElemType &e)
{
//插入元素e为新的栈顶元素
if(S.top - S.base >= S.stackSize)
{
//栈满
S.base = (SElemType *)realloc(S.base, sizeof(SElemType) * (S.stackSize + STACKINCREMENT));
if(!S.base)
exit(OVERFLOW);
S.top = S.base + S.stackSize;
S.stackSize += STACKINCREMENT;
}
*S.top++ = e;
return OK;
}
Status Pop(SqStack &S,SElemType &e)
{
//若栈不空,则删除S的栈顶元素
if(S.top == S.base )
return ERROR;
e = *--S.top;
return OK;
}
Status Disp(const SElemType &a)
{
printf("%d\t",a);
return OK;
}
Status StackTraverse(SqStack S, Status (*Visit)(const SElemType &e))
{
//从栈底到栈顶依次输出元素
if(S.top == S.base)
return ERROR;
while(S.base < S.top)
{
Visit(*S.base++);
}
return OK;
}
int main()
{
SqStack S;
int e;
InitStack(S);
for(int i = 1; i <= 10; ++i)
Push(S,i); //10个元素进栈
if(StackEmpty(S))
printf("栈空\n");
else
printf("栈不空\n");
printf("元素的个数为:%d 个\n",StackLength(S));
GetTop(S,e);
printf("从栈底到栈顶元素依次为:\n");
StackTraverse(S,Disp);
printf("\n");
printf("栈顶元素为: %d\n",e);
Pop(S,e);
printf("弹出栈顶元素为:%d\n",e);
printf("此时元素的个数为:%d 个\n",StackLength(S));
printf("从栈底到栈顶元素依次为:\n");
StackTraverse(S,Disp);
printf("\n");
ClearStack(S);
printf("栈已清空\n");
printf("此时元素的个数为:%d 个\n",StackLength(S));
return 0;
}
数据结构:栈的顺序存储实现
最新推荐文章于 2020-03-15 22:33:28 发布