#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define STACK_INIT_SIZE 100 //存储空间初始分配量
#define STACKINCREMENT 10 //存储空间分配增量
typedef int SElemType;
typedef int Status;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
//构造一个空栈
Status InitStack(SqStack *S)
{
S->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S->base)
{
printf("内存分配失败!\n");
exit(OVERFLOW);
}
S->top = S->base;
S->stacksize = STACKINCREMENT;
return OK;
}
//若栈不为空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR
Status GetTop(SqStack *S, SElemType *e)
{
if(S->top == S->base)
return ERROR;
*e = *(S->top - 1);
return OK;
}
//插入元素e为新的栈顶元素
Status Push(SqStack *S, SElemType e)
{
if(S->top - S->base >= STACK_INIT_SIZE) //栈满, 追加存储空间
{
S->base = (SElemType *)realloc(S->base, (S->stacksize + STACKINCREMENT) * sizeof(SElemType));
if(!S->base)
{
printf("内存分配失败!\n");
exit(OVERFLOW);
}
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*S->top++ = e;
return OK;
}
//若栈不为空,则删除S的栈顶元素,用e返回其值,并返回Ok;否则返回ERROR
Status Pop(SqStack *S, SElemType *e)
{
if(S->top == S->base)
return ERROR;
*e = *--S->top;
return OK;
}
Status visit(SElemType e)
{
printf("%d ", e);
return OK;
}
Status StackEmpty(SqStack S)
{
return S.top == S.base;
}
//输出栈S的数据
Status StackTravese(SqStack S, Status(visit)(SElemType))
{
while(S.top > S.base)
{
visit(*S.base ++);
}
printf("\n");
return OK;
}
//销毁栈S,使其不复存在
Status StackDestroy(SqStack *S)
{
free(S->base);
S->base = NULL;
S->top = NULL;
S->stacksize = 0;
return OK;
}
//清空栈S,保留栈底指针
void ClearStack(SqStack *S)
{
S->top = S->base;
}
int main()
{
int i;
SqStack S;
SElemType e;
if(InitStack(&S))
{
for(i = 0; i < 10; i++)
Push(&S, i);
printf("栈中元素依次为 :");
StackTravese(S, visit);
Push(&S, 90);
printf("插入元素后,栈中元素依次为 :");
StackTravese(S, visit);
GetTop(&S, &e);
printf("栈顶元素为:%d\n", e);
}
ClearStack(&S);
printf("清空后,栈空否:%d(1:空 0: 否)\n", StackEmpty(S));
StackDestroy(&S);
printf("销毁栈后, S.top = %u, S.base = %u, S.stacksize = %d\n", S.top, S.base, S.stacksize );
return 0;
}
数据结构——栈(C语言)
最新推荐文章于 2024-08-20 15:59:15 发布