考研进行时——严蔚敏书中栈的基础部分。
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int ElemType;
typedef struct _stack {
int sstacksize;
int* base;
int* top;
}sqStack;
/*
initStack(sqStack *s); //栈初始化函数
Push(sqStack *s, ElemType e); //压栈函数
ElemType Pop(sqStack *s, ElemType e); //出栈函数
ElemType getTop(sqStack *s); //取栈顶元素
int length(sqStack *s); //求栈的长度
bool JudgeEmpty(sqStack *s); //判断栈是否为空
*/
initStack(sqStack *s)
{
/*内存中开辟一段连续空间作为栈空间,首地址赋值给s->base*/
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if(!s->base) exit(0); /*分配空间失败*/
s->top = s->base; /*最开始,栈顶就是栈底*/
s->sstacksize = STACK_INIT_SIZE; /*最大容量为STACK_INIT_SIZE */
}
Push(sqStack *s, ElemType e){
if(s->top - s->base >= s->sstacksize){ /*栈满,追加空间*/
s->base = (ElemType *)realloc(s->base,(s->sstacksize +STACKINCREMENT)*sizeof(ElemType));
if(!s->base) exit(0); /*存储分配失败*/
s->top = s->base + s->sstacksize;
s->sstacksize = s->sstacksize + STACKINCREMENT; /*设置栈的最大容量*/
}
*(s->top) = e; /*放入数据*/
s->top++;
}
ElemType Pop(sqStack *s, ElemType e){
if(s->top==s->base )return -1; /*栈空判断*/
else
e=*(--s->top); /*保存数据*/
return e;
}
ElemType getTop(sqStack *s)
{
ElemType e;
e=*(s->top-1); /*指针先减一,保证top指针的值不变,再取指针对应的值*/
return e;
}
int length(sqStack *s)
{
if(s->top==s->base) /*如果栈顶和栈底指针相等,则返回零*/
return 0;
else
return s->top-s->base; /*否则返回二者差值*/
}
int JudgeEmpty(sqStack *s)
{
if(s->top==s->base) /*栈顶栈尾相等则空*/
return 1;
else
return 0;
}
int main()
{
sqStack *S;
int i,m;
initStack(S);
for(i=1;i<11;i++) /* 将数据压栈*/
{Push(S,i);}
if(!JudgeEmpty(S))printf("数据压栈成功!\n");
printf("栈的长度是:%d\n",length(S));
printf("压栈成功后栈顶元素是:");
printf("%d\n",getTop(S)); /* 打印栈顶元素*/
printf("5次出栈的元素:");
for(i=1;i<=5;i++) /* 将数据出栈*/
printf("%d ",Pop(S,m));
printf("\n5次出栈后栈的栈顶元素是:%d\n",getTop(S));
printf("5次出栈后栈的长度是:%d\n",length(S));
for(i=1;i<=5;i++)
Pop(S,m);
if(JudgeEmpty(S))printf("全部数据出栈成功!此时栈为空\n");
return 0;
}
结果截图: