堆栈就是栈通过数组的形式实现,我们都知道栈符合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=(STDataTy