#include<stdio.h>
#include<stdlib.h>
#define MAXSTACKSIZE 100
#define INTISTACKSIZE 10
//用内存动态分配定义栈的顺序存储结构
typedef struct
{
int *base;
int *top;
int stacksize;
}SqStack;
//构造一个空栈初始化
int InitStack(SqStack*S)
{
S->base=(int*)malloc(MAXSTACKSIZE*sizeof(int));
if(!S->base)
return 0;
S->top=S->base;
S->stacksize=MAXSTACKSIZE;
return 1;
}
//入栈
int Push(SqStack*S,int e)
{
//判断栈满,并为他增加分配内存空间
if(S->top==S->base+S->stacksize)
{
S->base=(int*)realloc(S->base,(S->stacksize+INTISTACKSIZE)*sizeof(int));
if(!S->base)
return 0;
S->top=S->base+S->stacksize;
S->stacksize=S->stacksize+INTISTACKSIZE;
}
*(S->top)=e;
S->top=S->top+1;
return 1;
}
//退栈
int Pop(SqStack*S,int *e)
{
if(S->top==S->base)
return 0;
S->top=S->top-1;
*e=*(S->top);
return 1;
}
//读取栈顶元素
int GetStackTop(SqStack S,int *e)
{
if(S.top==S.base)
return 1;
*e=*(S.top-1);
return *e;
}
//求栈中元素个数
int StackLength(SqStack S)
{
return S.top-S.base;
}
//输出栈元素
void PrintStack(SqStack *S)
{
if (S->top == S->base)
{
printf("栈为空");
}
else
{
int *p = S->base;
while (p < S->top)
{
printf("%d ", *p);
p++;
}
printf("\n");
}
}
int main()
{
SqStack S;
int *e;
InitStack(&S);
Push(&S,1);
Push(&S,2);
Push(&S,3);
PrintStack(&S);
Pop(&S,&e);
PrintStack(&S);
printf("%d\n",GetStackTop(S,&e));
printf("%d",StackLength(S));
return 0;
}