急求c语言关于堆栈的长度

2020-10-28 社会 84阅读
#include
#include
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct SqStack
{
int *base;
int *top;
int stacksize;
}
SqStack;
void InitStack(SqStack *S)//创建栈
{
S->base=(int*)malloc(STACK_INIT_SIZE*sizeof(int));
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
}
void Push(SqStack *S,int e)//进栈
{
if(S->top-S->base>=S->stacksize)
{
S->base=(int*)realloc(S->base,
(S->stacksize+STACKINCREMENT)*sizeof(int));
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*(S->top)=e;
S->top++;
}
int Pop(SqStack *S)//出栈
{
S->top --;
return *S->top;
}
int StackEmpty(SqStack *S)//判断栈是否为空
{
if(S->top == S->base )
return 1;
else
return 0;
}
int Length(SqStack *S)//求栈的长度
{
return(S->top - S->base);
}
void main()
{
SqStack S;
InitStack(&S);
Push(&S,1);
printf("长度为:%d\n", Length(&S));
Push(&S,2);
printf("长度为:%d\n", Length(&S));
Push(&S,3);
printf("长度为:%d\n", Length(&S));
Pop(&S);
printf("长度为:%d\n", Length(&S));
Push(&S,4);
printf("长度为:%d\n", Length(&S));
Push(&S,5);
printf("长度为:%d\n", Length(&S));
printf("栈里面还有:");
while(!StackEmpty(&S))
printf("%d ",Pop(&S));
}
就他了
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com