一.栈的概念
栈:一种特殊的线性表,只允许固定的一段插入和删除元素操作。进行数据插入的一端称为栈顶,另一端称为栈底。
二.用栈编写项目
(1)头文件的编写
typedef int SM;
typedef struct SL
{
SM* a;
SM top;
SM capacity;
}SL;
void stackinit(SL* ps);
void stackdestroy(SL* ps);
void stackpush(SL* ps,SM x);
void stackpop(SL* ps);
int stacktop(SL* ps);
bool stackempty(SL* ps);
int stacksize(SL* ps);
(2)初始化
void strackinit(SL* ps)
{
assert(ps);
ps->a=NULL;
ps->top=0;
ps->capacity=0;
}
(3)销毁
void stackdestory(SL* ps)
{
assert(ps);
free(ps->a);
ps->a=NULL;
ps->top=0;
ps->capacity=0;
}
(4)入栈
void stackpush(SL* ps)
{
assert(ps);
if(ps->top==ps->capacity)
{
int newcapacity=capacity=0?4:ps->capacity*2;
SM* temp=realloc(ps->a,sizeof(SM)*newcapacity);
if(temp==NULL)
{
exit(-1);
}
ps->a=temp;
ps->capacity=newcapacity;
}
ps->a[ps->top]=x;
ps->top++;
}
(5)出栈
void stackpop(SL* ps)
{
assert(ps);
assert(!stackempty(ps));
return ps->a[ps->top-1];
}
(6)判空
bool stackempty(SL* ps)
{
assert(ps);
return ps->top==0;
}
(7)栈的大小
int stacksize(SL* ps)
{
assert(ps);
retrun ps->top;
}