#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 10
#define STACK_INCREASEMENT 2
typedef int ElemType;
typedef struct SqStack {
ElemType* base;
ElemType* top;
int stacksize;
}SqStack,*pSqStack;
int initStack(pSqStack ps)
{
ps->base = (ElemType*)malloc(sizeof(ElemType)*STACK_INIT_SIZE);
if (!ps->base)return 0;
ps->top = ps->base;
ps->stacksize = STACK_INIT_SIZE;
return 1;
}
void destroyStack(pSqStack ps)
{
if (ps != NULL) {
free(ps->base);
ps->top = ps->base=NULL;
ps->stacksize = 0;
}
}
void clearStack(pSqStack ps)
{
ps->top = ps->base;
}
int isEmptyStack(pSqStack ps)
{
if (ps->base==ps->top)return 1;
return 0;
}
int lengthStack(pSqStack ps)
{
if (ps->base != NULL&&ps->top != NULL)
return ps->top - ps->base;
return 0;
}
int getTopStack(pSqStack ps,ElemType& e)
{
if (ps->base != ps->top) {
e = *(ps->top - 1);
return 1;
}
return 0;
}
int pushStack(pSqStack ps, ElemType e)
{
if (ps->top - ps->base >= ps->stacksize) {
ps->base = (ElemType*)realloc(ps->base,sizeof(ElemType)*(ps->stacksize + STACK_INCREASEMENT));
if (!ps->base)return 0;
ps->top = ps->base + ps->stacksize;
ps->stacksize += STACK_INCREASEMENT;
}
*(ps->top++) = e;
return 1;
}
int popStack(pSqStack ps, ElemType& e)
{
if (ps->base == ps->top)return 0;
e = *(--ps->top);
return 1;
}
void traverseStack(pSqStack ps, void(*callback)(ElemType))
{
ElemType* base = ps->base;
while (ps->top != base)
callback(*(base++));
printf("\n");
}
void print(ElemType e)
{
printf("%d ", e);
}
#include"stack.h"
int main()
{
SqStack s;
int i=0,e,state;
state = initStack(&s);
if (state)
printf("初始化栈成功!\n");
else
printf("初始化栈失败!\n");
printf("向栈顶压入元素(-999结束)!\n");
while (1) {
printf("压入第%d个元素:",(++i));
scanf("%d", &e);
if (e == -999)break;
state=pushStack(&s, e);
if (!state) {
printf("压栈失败!\n");
break;
}
}
printf("遍历栈中元素为:");
traverseStack(&s,print);
printf("栈容量:%d\n", s.stacksize);
printf("栈大小:%d\n", lengthStack(&s));
state=popStack(&s, e);
if (state)
printf("\n出栈成功!\n");
else
printf("\n出栈失败!\n");
printf("弹出栈顶元素为:%d\n", e);
printf("遍历栈中元素为:");
traverseStack(&s, print);
printf("栈容量:%d\n", s.stacksize);
printf("栈大小:%d\n", lengthStack(&s));
printf("\n清空栈!\n");
clearStack(&s);
printf("栈容量:%d\n", s.stacksize);
printf("栈大小:%d\n", lengthStack(&s));
printf("\n销毁栈!\n");
destroyStack(&s);
printf("栈容量:%d\n", s.stacksize);
printf("栈大小:%d\n", lengthStack(&s));
return 1;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2ddc00b4737a27b7cb7132287b783073.png)