栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端 称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
1.创建一个栈:
typedef struct stack{
SDataType *_array;
int _capacity;//有效元素最大个数
int _top;//栈顶
}Stack;
2:初始化:
void StackInit(Stack* ps)//初始化
{
assert(ps);
ps->_array = (SDataType*)malloc(sizeof(SDataType)* 3);
if (NULL == ps->_array)
exit(1);
ps->_capacity = 3;
ps->_top = 0;
}
3.销毁
void StackDestory(Stack* ps)//销毁
{
assert(ps);
if (ps->_array)
{
free(ps->_array);
ps->_array = NULL;
ps->_capacity = 0;
ps->_top = 0;
}
}
4.增容
void _CheckCapacity(Stackps)//增容
{
assert(ps);
if (ps->_top == ps->_capacity)
{
ps->_array = (SDataType)realloc(ps->_array, sizeof(SDataType)*(ps->_capacity + 3));
ps->_capacity <<= 1;
}
}
5.压栈
id Stackpush(Stack*ps, SDataType data)//压栈
{
assert(ps);
_CheckCapacity(ps);
ps->_array[ps->_top++] = data;
}
6.出栈
void StackPop(Stack* ps)//出栈
{
assert(ps);
ps->_top--;
}
7.
7.取栈顶元素
SDataType StackTop(Stack* ps)//取栈顶元素
{
assert(ps);
return ps->_array[ps->_top - 1];
}
8.判空
int StackEmpty(Stack* ps)//判空
{
assert(ps);
return ps->_top == 0;
}
9.栈
的大小
int StackSize(Stack* ps)//栈的大小
{ a
ssert(ps);
return ps->_top;
}