堆栈就是栈通过数组的形式实现,我们都知道栈符合FILO即First In Last Out先进后出、后进先出的原则。栈顶指针top如果赋值-1,那么top指向栈顶元素;如果top赋值0,那么top指向栈顶上方的元素。下面我们来实现堆栈的基本操作(附有其他操作):
1.初始化
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
typedef int STDataType;
typedef struct Stack{
STDataType *a;//数组指针
int capacity;
int top;
}ST;
void InitStack(ST*ps){
assert(ps);
ps->a=(STDataType*)malloc(sizeof(STDataType)*4);
ps->capacity=4;
ps->top=0;
}
2.入栈
void PushStack(ST*ps,STDataType x){
assert(ps);
ps->a[ps->top]==x;
ps->top++;
if(ps->capacity==ps->top){
STDataType*tmp=(STDataType*)realloc(ps->a,ps->capacity*2*sizeof(STDataType));
if(tmp==NULL)
exit(-1);
else{
ps->a=tmp;
ps->capacity*=2;
}
}
}
3.出栈
STDataType PopStack(ST*ps){
assert(ps);
if(ps->capacity==ps->top){
printf("没有元素可打印!");
exit(-1);
}
else
return ps->a[--ps->top];
}
4.打印
void PrintStack(ST*ps){
assert(ps);
while(ps->top==0)
printf("%d ",ps->a[--ps->top]);
}
5.销毁
void DestroyStack(ST*ps){
assert(ps);
free(ps->a);
ps->a==NULL;
ps->top=ps->capcity=0;
}
6.判空
void StackEmpty(ST*ps){
assert(ps);
return ps->top?1:0;
}//三目表达式
7.计算空间大小
void StackSize(ST*ps){
assert(ps);
return ps->top;
}